[R] Fw: Removing blank cells and shifting data in df
arun
smartpink111 at yahoo.com
Sat Mar 22 14:51:54 CET 2014
Hi,May be this helps:
dat1 <- read.table(text="ID 1 2 3 4 5 6
A 1988 1995 2000 2000 2007
B 1995 1997 2000 2001
C 2001 2008 2010",sep="",header=TRUE,check.names=FALSE, fill=TRUE,stringsAsFactors=FALSE)
dat1[is.na(dat1)] <-""
dat1
# ID 1 2 3 4 5 6
#1 A 1988 1995 2000 2000 2007
#2 B 1995 1997 2000 2001
#3 C 2001 2008 2010
str(dat1)
#'data.frame': 3 obs. of 7 variables:
# $ ID: chr "A" "B" "C"
# $ 1 : int 1988 1995 2001
# $ 2 : int 1995 1997 2008
# $ 3 : int 2000 2000 2010
# $ 4 : chr "2000" "2001" ""
# $ 5 : chr "2007" "" ""
# $ 6 : chr "" "" ""
#Suppose, you already read the data as shown in the post:
dat <- read.csv("Laura.csv",header=TRUE,stringsAsFactors=FALSE,check.names=FALSE)
dat[is.na(dat)] <- ""
dat
# ID 1 2 3 4 5 6
#1 A 1998 1995 2000 2000 2007
#2 B 1995 1997 2000 2001
#3 C 2001 2008 2010
dat[,-1] <- do.call(rbind,lapply(seq_len(nrow(dat)),function(i) {x <- dat[i,-1]; indx <- x!=""; c(x[indx],rep("",length(x)-length(x[indx])))}))
dat
# ID 1 2 3 4 5 6
#1 A 1998 1995 2000 2000 2007
#2 B 1995 1997 2000 2001
#3 C 2001 2008 2010
A.K.
I would like to remove null values in a dataframe and shift all data left.
I have something like:
ID 1 2 3 4 5 6
A 1988 1995 2000 2000 2007
B 1995 1997 2000 2001
C 2001 2008 2010
I want something like:
ID 1 2 3 4 5 6
A 1988 1995 2000 2000 2007
B 1995 1997 2000 2001
C 2001 2008 2010
Any suggestions on how to accomplish this?
More information about the R-help
mailing list