[R] splitting a long dataframe

arun smartpink111 at yahoo.com
Wed Dec 26 06:24:46 CET 2012


Hi,
You can do this either by:
with(data1,aggregate(y,by=list(x),function(x) x)) #2nd column is a list here
#or
 res1<-split(seq(nrow(data1)),data1$x)
#or
res1<-tapply(data1$y,list(data1$x),function(x) x)
res2<- t(sapply(res1,`[`,1:max(sapply(res1,length))))
res2[cbind(c(rep(8,4),rep(9,4)),c(1:4,1:4))]<-res2[cbind(c(rep(8,4),rep(9,4)),c(3,1,4,2,3,1,4,2))]
 res2
#        [,1] [,2] [,3] [,4]
#0:00:00    1    8   17   24
#0:30:00    2    9   18   25
#1:00:00    3   10   19   26
#1:30:00    4   11   20   27
#2:00:00    5   12   21   28
#2:30:00    6   13   22   29
#3:00:00    7   14   23   30
#3:30:00   NA   15   NA   31
#4:00:00   NA   16   NA   32

#or
res3<-do.call(rbind,lapply(res1,function(x) {if(length(x) < 4) c(NA,x[1],NA,x[2]) else x}))
 tail(res3)
 #       [,1] [,2] [,3] [,4]
#1:30:00    4   11   20   27
#2:00:00    5   12   21   28
#2:30:00    6   13   22   29
#3:00:00    7   14   23   30
#3:30:00   NA   15   NA   31
#4:00:00   NA   16   NA   32

identical(res2,res3)
#[1] TRUE

A.K.




----- Original Message -----
From: Swagath <swagathnavin82 at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Tuesday, December 25, 2012 12:52 PM
Subject: [R] splitting a long dataframe

Dear all...Merry Christmas

I would like to split a long dataframe. The dataframe looks like this

x<-c('0:00:00', '0:30:00', '1:00:00', '1:30:00', '2:00:00', '2:30:00', '3:00:00', '0:00:00', '0:30:00', '1:00:00', '1:30:00', '2:00:00', '2:30:00', '3:00:00', '3:30:00', '4:00:00','0:00:00', '0:30:00', '1:00:00', '1:30:00', '2:00:00', '2:30:00', '3:00:00', '0:00:00', '0:30:00', '1:00:00', '1:30:00', '2:00:00', '2:30:00', '3:00:00' , '3:30:00', '4:00:00')

y=seq(1:32)

data1=data.frame(x,y)

i want to split in such a way that the output looks like

0:00:00  1  8 17 24
0:30:00  2  9 18 25
1:00:00  3 10 19 26
1:30:00  4 11 20 27
2:00:00  5 12 21 28
2:30:00  6 13 22 29
3:00:00  7 14 23 30
3:30:00 NA 15 NA 31
4:00:00 NA 16 NA 32

any ideas or functions that i look into for doing this?
Thanks a lot for your help and time.

Cheers,
Swagath

______________________________________________
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.





More information about the R-help mailing list