Split column
On Nov 24, 2009, at 12:53 PM, Adaikalavan wrote:
Not very elegant but this does the trick: df <- cbind( var1=c(1,3,2,1,2), var2=c(3,1,1,2,3) )
df <- data.frame(id=1:5, df)
data.frame(id=df$id,
var1.1 = (df$var1<3) + 2*(df$var1==3), # 1 for < 3; 2
for 3
var1.2 = (df$var1==1) + 2*(df$var1>=2), # 1 for =1; 2
otherwise
var2.1 = (df$var2<3) + 2*(df$var2==3), # lather, rinse,
var2.2 = (df$var2==1) + 2*(df$var2>=2) ) # repeat
Offered not for its superior readability, since in that respect it is
inferior to Ramasamy's solution below, but rather for possibility that
it may run faster.
David > > out <- df > out[ which(df==1, arr.ind=T) ] <- "1&1" > out[ which(df==2, arr.ind=T) ] <- "1&2" > out[ which(df==3, arr.ind=T) ] <- "2&2" > > outlist <- apply(out, 2, strsplit, split="&") > do.call( "cbind.data.frame", lapply( outlist, do.call, > what="rbind" ) ) > var1.1 var1.2 var2.1 var2.2 > 1 1 1 2 2 > 2 2 2 1 1 > 3 1 2 1 1 > 4 1 1 1 2 > 5 1 2 2 2 > > Please check. > > Regards, Adai > > > > Lisaj wrote: >> Hello, R users, >> I have a dataset that looks like this: id var1 var2 1 >> 1 3 2 3 1 3 2 1 4 1 >> 2 5 2 3 I want to split one column to two columns >> with 1 = 1 and 1, 2 = 1 and 2, 3 = >> 2 and 2: id var1.1 var1.2 var2.1 var2.2 1 1 >> 1 2 2 2 2 2 1 1 >> 3 1 2 1 1 >> 4 1 1 1 2 >> 5 1 2 2 2 >> Can anyone please help how to get this done? Thanks a lot in advance >> Lisa >> > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. David Winsemius, MD Heritage Laboratories West Hartford, CT