Sunday, December 28, 2008

reshape

# wide to long
d1<-data.frame(subject=c("an1","an2"),eat1=1:2,eat3=5:6,trt=c("t1","t2"))
d1.1<-reshape(d1, idvar="subject",varying=list(c("eat1","eat3")),v.names="eat",direction="long")
d1.2<-reshape(d1, idvar="subject",varying=list(c("eat1","eat3")),v.names="eat",times=c(1,3),timevar="week",direction="long")

d2<-data.frame(subject=c("an1","an2"),eat1=1:2,eat3=5:6,gain1=14:15,gain3=20:21,trt=c("t1","t2"))
d2.1<-reshape(d2,idvar="subject",varying=list(c("eat1","eat3"),c("gain1","gain3")),v.names=c("eat","gain"),times=c(1,3),timevar="week",direction="long")
d2.2<-reshape(d2,idvar="subject",varying=list(c("eat1","eat3")),v.names="eat",times=c(1,3),timevar="week",direction="long")
d2.3<-reshape(d2,idvar="subject",varying=list(c("eat1","eat3")),drop=c("gain1","gain3"),v.names="eat",times=c(1,3),timevar="week",direction="long")

# long to wide
reshape(d1.2,idvar="subject",timevar="week",v.names="eat",direction="wide")
reshape(d2.1,idvar="subject",timevar="week",v.names=c("eat","gain"),direction="wide")

from Reshaping data with the reshape function in R by Soren Hojsgaard

No comments: