Search code examples
rxtsrollapply

R xts: apply over a rolling window


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.


Solution

  • 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.