Skip to content
Prev 323133 / 398502 Next

how to calculate the mean in a period of time?

Hi,
Your question is still not clear.
May be this helps:

dat2<- read.table(text="
patient_id????? t???????? scores
1????????????????????? 0??????????????? 1.6
1????????????????????? 1??????????????? 2.6
1????????????????????? 2???????????????? 2.2
1????????????????????? 3???????????????? 1.8
2????????????????????? 0????????????????? 2.3
2?????????????????????? 2???????????????? 2.5
2????????????????????? 4????????????????? 2.6
2?????????????????????? 5???????????????? 1.5
",sep="",header=TRUE)

library(plyr)
?dat2New<-ddply(dat2,.(patient_id),summarize,t=seq(min(t),max(t)))
?res<-join(dat2New,dat2,type="full")
res1<-do.call(rbind,lapply(split(res,res$patient_id),function(x) {x1<-x[x$t!=0,];do.call(rbind,lapply(split(x1,((x1$t-1)%/%3)+1),function(y) {y1<-if(any(y$t==1)) rbind(x[x$t==0,],y) else y; data.frame(patient_id=unique(y1$patient_id),scores=mean(y1$scores,na.rm=TRUE))}) ) }))
?row.names(res1)<-1:nrow(res1)
res1$period<-with(res1,ave(patient_id,patient_id,FUN=seq))
?res1
#? patient_id scores period
#1????????? 1?? 2.05????? 1
#2????????? 2?? 2.40????? 1
#3????????? 2?? 2.05????? 2


A.K.
Message-ID: <1367953733.81813.YahooMailNeo@web142601.mail.bf1.yahoo.com>
In-Reply-To: <CAMiZAio5Uhh8cpmRe3tTOzpPgVZrk33Jw56PJmAm4OvKuttBGA@mail.gmail.com>