Question

I would like to compute a moving average (ma) over some time series data but I would like the ma to consider the order n starting from the rightmost of my series so my last ma value corresponds to the ma of the last n values of my series. The desired function rightmost_ma would produce this output:

data <- seq(1,10)
> data
[1]  1  2  3  4  5  6  7  8  9 10

rightmost_ma(data, n=2)
NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 

I was reviewing the different ma possibilities e.g. package forecast and could not find how to cover this use case. Note that the critical requirement for me is to have valid non NA ma values for the last elements of the series or in other words I want my ma to produce valid results without "looking into the future".

Was it helpful?

Solution

Take a look at rollmean function from zoo package

> library(zoo)
> rollmean(zoo(1:10), 2, align ="right", fill=NA)
  1   2   3   4   5   6   7   8   9  10 
 NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 

you can also use rollapply

> rollapply(zoo(1:10), width=2, FUN=mean, align = "right", fill=NA)
  1   2   3   4   5   6   7   8   9  10 
 NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5 

OTHER TIPS

I think using stats::filter is less complicated, and might have better performance (though zoo is well written).

This:

filter(1:10, c(1,1)/2, sides=1)

gives:

Time Series:
Start = 1
End = 10
Frequency = 1
[1]  NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5

If you don't want the result to be a ts object, use as.vector on the result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top