Posted this on the R4DS-slack, and was redirected here.
Does anyone have a good grasp of the Slider-package and it's slide_mean function? It does not behave as I thought it would.
library(slider)
library(tidyverse)
tribble(~date, ~value,
1, 0.557,
2, 0.674,
3, 0.586,
4, 0.851,
5, 0.151,
6, 0.154) %>%
mutate(roll_avg = slide_mean(value, before = 4, after = 0))
#> # A tibble: 6 x 3
#> date value roll_avg
#> <dbl> <dbl> <dbl>
#> 1 1 0.557 0.557
#> 2 2 0.674 0.616
#> 3 3 0.586 0.606
#> 4 4 0.851 0.667
#> 5 5 0.151 0.564
#> 6 6 0.154 0.483
(.557+.674+.586+.851)/4
#> [1] 0.667
(.674+.586+.851+.151)/4
#> [1] 0.5655
Created on 2021-06-10 by the reprex package (v2.0.0)
I would expect the rolling average for date == 4 to be equal to
(.557+.674+.586+.851)/4
which my calculator gets to 0.667, as does slide_mean
. Then I expect it to "jump" forward one step, and take the average of date 2 to 5, ie:
(.674+.586+.851+.151)/4
which my calculator gets to 0.5655. slide_mean
however get it to 0.5638. Anyone know what's wrong? Or what I should do to get it to behave as I expected?
I'm on an M1 Macbook Pro, using R 4.1.0 and Rstudio 1.4.1717, if that's something that could be causing the issue