runningbirds runningbirds - 11 months ago 47
R Question

Rolling means and applying means at beginning of a series of data

I want to do a rolling mean of the the previous 4 values in a dataset. However, for the beginning, since there is not 4 values, I want to do the rolling mean of 1/2/3 observations. How do I do this?

df= data.frame(a=c(1,2,3,4,5))
df$answer = rollapply(df$a, 4,mean)

For example, row 1 would have a value of 1, row 2 would have a value of (1+2)/2=1.5, row 3 would have a value of 6/3=2.

I want to do rolling means of 4 periods but in periods with fewer months, I want to do the mean of the maximum periods allowed.

Answer Source

Use right aligment with partial=TRUE, i.e. rollapplyr(..., partial=TRUE) or rollapply(..., align = "right", partial=TRUE). Here we use rollapplyr:

rollapplyr(df$a, 4, mean, partial = TRUE)