Re: [R] Aggregate lag

From: Achim Zeileis <Achim.Zeileis_at_wu-wien.ac.at>
Date: Tue 10 May 2005 - 22:23:59 EST

On Tue, 10 May 2005 12:55:52 +0200 Matthieu Cornec wrote:

> hello,
>
> Does anybody know how to aggregate a lag series ?
> when I try to use aggregate I get the following message
>
> > try<-ts(1:100,start=c(1985,1),freq=12)
> > aggregate(try,4,mean,na.rm=T)
> Qtr1 Qtr2 Qtr3 Qtr4
> 1985 2 5 8 11
> 1986 14 17 20 23
> 1987 26 29 32 35
> 1988 38 41 44 47
> 1989 50 53 56 59
> 1990 62 65 68 71
> 1991 74 77 80 83
> 1992 86 89 92 95
> 1993 98
> > aggregate(lag(try,-1),4,mean,na.rm=T)
> Error in rep.int("", start.pad) : invalid number of copies in rep()

The ts-method seems to expect full blocks of observations. Note, that also the last observation (100 in April 1993) is dropped from the aggregate call above. I'm not sure what is the recommended way to circumvent this problem with "ts": probably, you have to do some padding with NAs yourself.

Example:
R> x <- ts(1:20,start=c(1990,1),freq=12) R> aggregate(window(x, start = c(1990, 1), end = c(1991, 9),

     extend = TRUE), 4, mean, na.rm = TRUE)
     Qtr1 Qtr2 Qtr3 Qtr4
1990  2.0  5.0  8.0 11.0
1991 14.0 17.0 19.5     
R> aggregate(window(lag(x, k = -1), start = c(1990, 1),
     end = c(1991, 9), extend = TRUE), 4, mean, na.rm = TRUE)
     Qtr1 Qtr2 Qtr3 Qtr4
1990  1.5  4.0  7.0 10.0
1991 13.0 16.0 19.0     

In zoo this can be done a bit easier:
R> z <- zooreg(1:20, start = yearmon(1990), freq = 12) R> aggregate(z, as.yearqtr(time(z)), mean) 1990 Q1 1990 Q2 1990 Q3 1990 Q4 1991 Q1 1991 Q2 1991 Q3

    2.0 5.0 8.0 11.0 14.0 17.0 19.5 R> aggregate(lag(z, k = -1), as.yearqtr(time(lag(z, -1))), mean) 1990 Q1 1990 Q2 1990 Q3 1990 Q4 1991 Q1 1991 Q2 1991 Q3

    1.5 4.0 7.0 10.0 13.0 16.0 19.0

hth,
Z  

> Matthieu
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Tue May 10 22:40:07 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:40 EST