[R] reshape question

Ista Zahn istazahn at gmail.com
Fri Feb 8 15:15:11 CET 2008


I know there are a lot of reshape questions on the mailing list, but I  
haven't been able to find an answer to this particular issue.

I am trying to get a datafame structured like this:

 > sub <- rep(1:5)
 > ta1 <- rep(1,5)
 > ta2 <- rep(2,5)
 > tb1<- rep(3,5)
 > tb2 <- rep(4,5)
 > DF <- data.frame(sub,ta1,ta2,tb1,tb2)
 > DF
   sub ta1 ta2 tb1 tb2
1   1   1   2   3   4
2   2   1   2   3   4
3   3   1   2   3   4
4   4   1   2   3   4
5   5   1   2   3   4

into a form like this:

     sub time x1 x2
1.1   1    1  1  3
1.2   1    2  2  4
2.1   2    1  1  3
2.2   2    2  2  4
3.1   3    1  1  3
3.2   3    2  2  4
4.1   4    1  1  3
4.2   4    2  2  4
5.1   5    1  1  3
5.2   5    2  2  4

using the "reshape" command. But when I try reshaping I don't get the  
desired structure:

 > DF.L <- reshape(DF, varying = 2:5, idvar="sub", v.names = c("x1",  
"x2"), times=c(1,2), direction="long")
 > library(doBy)
 > orderBy(~sub, data=DF.L)
     sub time x1 x2
1.1   1    1  1  2
1.2   1    2  3  4
2.1   2    1  1  2
2.2   2    2  3  4
3.1   3    1  1  2
3.2   3    2  3  4
4.1   4    1  1  2
4.2   4    2  3  4
5.1   5    1  1  2
5.2   5    2  3  4

I can get the desired result by rearranging the original dataframe, like
 > DF2 <- data.frame(sub,ta1,tb1,ta2,tb2)

before running the reshape command, but I'm hoping someone knows a way  
to do the desired reshaping without this step, as it becomes very time  
consuming with large numbers of repeated measurements.

Thanks,
Ista



More information about the R-help mailing list