runningbirds - 9 months ago 38

R Question

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?

`library(zoo)`

df= data.frame(a=c(1,2,3,4,5))

df$answer = rollapply(df$a, 4,mean)

#help

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

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)
```

Source (Stackoverflow)