Re: [R] aggregate.ts help

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Sun, 6 Jan 2008 17:44:54 -0500

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



R-help_at_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. Received on Sun 06 Jan 2008 - 22:48:59 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 07 Jan 2008 - 00:30:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive