0

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)?

Max
  • 487
  • 5
  • 19
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jun 29 '20 at 21:32
  • For x1=c(1,2,3,4,5,6), I would like to calculate the moving average of a point and its k previous points. If k = 1, the output would be (NA, 1.5, 2.5, 3.5, 4.5, 5.5). For k=2, (NA, NA, 2, 3, 4, 5). I don't see a way to do this for arbitrary k using ma in the forecast library. – Max Jun 29 '20 at 21:37

1 Answers1

1

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
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341