I want to make a moving average from the previous 4 values ββin a dataset. However, for starters, since there are no 4 values, I want to make an average value for 1/2/3 of the observations. How to do it?
library(zoo) df= data.frame(a=c(1,2,3,4,5)) df$answer = rollapply(df$a, 4,mean)
For example, line 1 will have the value 1, line 2 will have the value (1 + 2) / 2 = 1.5, line 3 will have the value 6/3 = 2.
I want to cast from 4 periods, but in periods with fewer months I want to make the average of the allowable maximum periods.
source share