If you've used the purrr package and enjoy its API, you might like slider
library(slider)
library(tibble)
df <- tibble(
x = c(2,4,1,5,9,5,7,5,9,8,7,5,6,8,4,2,8,1,9,3,8,5,11,16,10),
# Current value + 4 before it
mean = slide_mean(x, before = 4, complete = TRUE)
)
df
#> # A tibble: 25 x 2
#> x mean
#> <dbl> <dbl>
#> 1 2 NA
#> 2 4 NA
#> 3 1 NA
#> 4 5 NA
#> 5 9 4.2
#> 6 5 4.8
#> 7 7 5.4
#> 8 5 6.2
#> 9 9 7
#> 10 8 6.8
#> # … with 15 more rows
Created on 2021-05-06 by the reprex package (v1.0.0)