3
I need to make a simple 7-day moving average on R, I’m using the function rollmean
package zoo
, but the values being returned are incorrect.
Example:
library(zoo)
teste <- sample(1:50)
mean <- rollmean(teste, 7, align = "right")
teste <- cbind(teste, mean)
Upshot:
teste mean
42 27.42857
21 22.85714
11 25.57143
48 29.85714
33 34.85714
29 36.28571
8 34.57143
10 29.28571
40 25.85714
41 26.85714
In the last value, which returned 26.85714, it should return 25.57143, which would be the average of the 7 previous days (40, 10, 8, 29, 33, 48, 11). What’s going on?
Obs.: I know the function sample
generates random values and that its execution will not result in the same values shown in the example.
Can use
set.seed()
to make random data generation reproducible.– Carlos Eduardo Lagosta
You should use set.Seed(). Please read the good practice manual here in R. The examples need to be reproducible in order to analyze. For this, it is important to specify the Seed when you use random data. Its use is very simple, just specify any number for example
set.seed(123)
. In that your question was not crucial, but there may be others that you will end up unanswered only because it was not reproducible.– A Neto