Calculating moving average


I'm trying to use R to calculate the moving average over a series of values in a matrix. The normal R mailing list search hasn't been very helpful though. There doesn't seem to be a built-in function in R will allow me to calculate moving averages. Do any packages provide one? Or do I need to write my own?

12/13/2017 8:24:00 PM

Accepted Answer

  • Rolling Means/Maximums/Medians in the zoo package (rollmean)
  • MovingAverages in TTR
  • ma in forecast
8/11/2017 8:04:21 PM

Or you can simply calculate it using filter, here's the function I use:

ma <- function(x, n = 5){filter(x, rep(1 / n, n), sides = 2)}

If you use dplyr, be careful to specify stats::filter in the function above.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow