rguides

How to Calculate Rolling Means in R

Calculate rolling means to smooth out short-term fluctuations and reveal longer-term trends in time series data. The window size controls the trade-off: a wider window produces a smoother line but lags behind rapid changes, while a narrow window tracks movement more closely but retains more noise. For exploratory work, a centered window of 7 or 14 periods is a practical default — it balances responsiveness with noise reduction. In forecasting or backtesting scenarios, use a trailing window that only looks backward to avoid leaking future information into past estimates.

library(dplyr)
library(slider)

df <- data.frame(
  date = seq(as.Date("2024-01-01"), by = "day", length.out = 30),
  value = cumsum(rnorm(30))
)

df <- df %>%
  mutate(
    rolling_mean_7 = slide_dbl(value, mean, .before = 3, .after = 3),
    rolling_mean_3 = slide_dbl(value, mean, .before = 1, .after = 1)
  )

The slider package gives you centered windows by default: .before = 3, .after = 3 produce a 7-period window with equal points on each side. The zoo package offers rollapply() as an alternative:

library(zoo)

df$rolling_mean <- rollapply(df$value, width = 7, FUN = mean, align = "center", fill = NA)

For real-time scenarios, use trailing windows that only look backward. In slide_dbl(), set .before = 6, .after = 0 for a 7-period trailing window. In rollapply(), set align = "right". Trailing windows avoid using future data to compute a past value — critical when you are simulating a live trading or monitoring scenario. Positions at the edges without enough neighbors return NA by default.

See also