[R] reshape question
Chuck Cleland
ccleland at optonline.net
Fri Feb 8 15:28:26 CET 2008
On 2/8/2008 9:15 AM, Ista Zahn wrote:
> 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
The varying argument to reshape() can be a list. For example:
DF.long <- reshape(DF, varying = list(c("ta1","ta2"),
c("tb1","tb2")),
idvar="sub",
v.names = c("x1","x2"),
times=c(1,2),
direction="long")
DF.long[order(DF.long$sub),]
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
> 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
>
> ______________________________________________
> 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.
--
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894
More information about the R-help
mailing list