Skip to content
Prev 69445 / 398513 Next

Aggregate lag

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

            
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