How to calculate a rolling mean in R

· 1 min read · Updated March 14, 2026 · beginner
r time-series rolling-window dplyr zoo

A rolling mean (also called a moving average) smooths out short-term fluctuations to reveal longer-term trends in your data.

With dplyr and slider

The slider package provides powerful rolling window functions:

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

With zoo

The zoo package provides rollapply() for rolling calculations:

library(zoo)

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

See Also