rollapply time series in R (zoo) on backward looking data
Asked Answered
C

1

6

I would like to use the zoo function rollapply to apply a function (for example mean) on a time series but only using the last N known points. For example:

x = zoo(c(1,2,3,4), order.by=c(10,11,12,13))

rollmean(x,2)

Produces:

10 11 12

1.5 2.5 3.5

I would like to produce a series that would have date entries of 11, 12, 13 and values of 1.5, 2.5, 3.5. The values seem correct but the dates that rollmean outputs don't seem to correspond to what I would like. I'm a bit worried about just assigning the dates I want to the zoo object using time(x)<- because I'm not sure that rollapply is actually doing the right thing. Help is appreciated as always.

Chlorpromazine answered 3/12, 2011 at 21:2 Comment(1)
I believe this is the align parameter in rollapply. Is this correct? The documentation is a bit ambiguous but playing around with it seems to point to this.Chlorpromazine
J
5

Specify align="right" or just use rollmeanr (only in recent versions of zoo though).

> rollmean(x,2,align="right")
 11  12  13 
1.5 2.5 3.5
> rollmeanr(x,2)
 11  12  13 
1.5 2.5 3.5 
Julianjuliana answered 3/12, 2011 at 21:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.