# [R] how to calculate the mean in a period of time?

arun smartpink111 at yahoo.com
Tue May 7 21:08:53 CEST 2013

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

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

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 <guanguanluo at gmail.com>
To: arun <smartpink111 at 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 <smartpink111 at 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
>

```