R xts: apply over a rolling window

1.4k views Asked by At

I wish to execute a function FUN over a rolling window of 1 year. My xts has not the same number of points per year. How can I do that in an efficient way?

P.S. usually to execute a FUN over a fixed number of datapoints (for instance 100) I use:

as.xts(rollapply(data = zoo(indicator), FUN = FUN, width = 100, align = "right"))

but obviously this doesn't work if there are not always the same number of points per year.

2

There are 2 answers

0
RockScience On BEST ANSWER

I'll try to answer my own question: One way to do that is:

  1. First to NA-pad the time series so that there is one datapoint per day (or any unit relevant for your case),
  2. (optional, depending on your FUN) Then to use na.locf to carry over the last data to fill the holes.
  3. Finally to use the usual rollapply as shown in the question, over a fixed number of datapoints that corresponds to 1 year.
0
Swyler On

Your can use the apply.yearly(x, FUN, ...) function from the xts library.

dat <- xts(rnorm(1000), order.by = as.Date(1:1000))
plot(dat)
apply.yearly(dat, mean)