Search code examples
rforecast

Moving average in negative direction (ma in R forecast)


For a series

X=(x_1,x_2,...x_t-2, x_t-1, x_t)

I would like to compute a moving average for each point with respect to the previous k time steps. For example, if k = 2, I want to return:

X =(NA, (x_1+x_2)/2 ... (x_t-2 + x_t-3)/2, (x_t-2 + x_t-1)/2, (x_t + x_t-1)/2)

If I use the moving average function ma, e.g.

ma(X, order = 2, centre = TRUE)

I get the average of each point and its neighbor in the positive and negative direction, while setting centre=FALSE calculates the moving average with respect to the positive direction. Is there a simple way to have point t as the running average of (t-k+1...t)?


Solution

  • Assuming test input X as shown this takes the mean of the current and prior value. Note the r on the end of rollmeanr which tells it to use the right aligned version rather than the center aligned version.

    library(zoo)
    
    X <- 1:10 # test input
    
    rollmeanr(X, 2, fill = NA)
    ## [1]  NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5
    

    so does this (no packages):

    n <- length(X)
    c(NA, (X[-1] + X[-n])/2)
    ## [1]  NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5
    

    and this somewhat more general base R approach (also no packages):

    k <- 2
    c(rep(NA, k-1), rowMeans(embed(X, k)))
    ## [1]  NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5