[R] aggregate.ts help

Gabor Grothendieck ggrothendieck at gmail.com
Sun Jan 6 23:44:54 CET 2008


On Jan 6, 2008 5:17 PM, tom soyer <tom.soyer at gmail.com> wrote:
> Hi,
>
> I have a ts object with a frequency of 4, i.e., quarterly data, and I would
> like to calculate the mean for each quarter. So for example:
>
> > ts.data=ts(1:20,start=c(1984,2),frequency=4)
> > ts.data
>     Qtr1 Qtr2 Qtr3 Qtr4
> 1984         1    2    3
> 1985    4    5    6    7
> 1986    8    9   10   11
> 1987   12   13   14   15
> 1988   16   17   18   19
> 1989   20
>
> If I do this manually, the mean for the 1st quarter would be
> mean(c(4,8,12,16,20)), which is 12. But I am wondering if there is a R
> function that could do this faster. I tried aggregate.ts but it didn't work:
>
> > aggregate(ts.data,nfrequency=4,mean)
>     Qtr1 Qtr2 Qtr3 Qtr4
> 1984         1    2    3
> 1985    4    5    6    7
> 1986    8    9   10   11
> 1987   12   13   14   15
> 1988   16   17   18   19
> 1989   20
>
> Does anyone know what am I doing wrong?

aggregate.ts aggregates to produce series of coarser granularity
which is not what you want.  You want the ordinary aggregate:

aggregate(c(ts.data), list(qtr = cycle(ts.data)), mean)

# or tapply:

tapply(ts.data, cycle(ts.data), mean)

See ?aggregate




More information about the R-help mailing list