r - Rolling means and applying means at beginning of a series of data -
i want rolling mean of the previous 4 values in dataset. however, beginning, since there not 4 values, want rolling mean of 1/2/3 observations. how do this?
library(zoo) df= data.frame(a=c(1,2,3,4,5)) df$answer = rollapply(df$a, 4,mean) #help
for example, row 1 have value of 1, row 2 have value of (1+2)/2=1.5, row 3 have value of 6/3=2.
i want rolling means of 4 periods in periods fewer months, want mean of maximum periods allowed.
use right aligment partial=true
, i.e. rollapplyr(..., partial=true)
or rollapply(..., align = "right", partial=true
). here use rollapplyr
:
rollapplyr(df$a, 4, mean, partial = true)