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. ________________________________ From: GUANGUAN LUO <guanguan...@gmail.com> To: arun <smartpink...@yahoo.com> Sent: Tuesday, May 7, 2013 11:29 AM Subject: Re: how to calculate the mean in a period of time? Yes , as you have said, probably , it's not continuous. 2013/5/7 arun <smartpink...@yahoo.com> Hi, >Your question is not clear. You mentioned to calculate the mean of 3 months, >but infact you added the scores for t=0,1,2,3 as first 3 months, then possibly >4,5,6 as the next. So, it is not exactly three months. Isn't it? > > >Dear R experts, >sorry to trouble you again. >My data is like this now : >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 > >I want to calculate the mean of period of 3 months, just get a table like this > >patient_id period scores >1 1 2.05 >(1.6+2.6+2.2+1.8)/4 >2 1 2.4 >(2.3+2.5)/2 >2 2 2.05 >(2.6+1.5)/2 > >thank you in avance > ______________________________________________ R-help@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.