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

Thursday, December 18, 2008

Paired t-test with Mixed Models


library(MASS)
library(nlme)

# simulated a dataset
paired<-mvrnorm(n=30,mu=c(10,10.2),Sigma=matrix(c(5,4,4,5),2,2))

before<-paired[,1]
after<-paired[,2]


# paired t-test
t.test(before,after,paired=TRUE)



### Mixed Models for a paired t-test
# reshape data for mixed models
y<-c(before,after)
id<-rep(c(1:length(before)),2)
time<-c(rep(0,length(before)),rep(1,length(after)))


# fit mixed models
summary(lme(y~time, random=~1|id))