A moving function in R but not with leading NA's

105 views Asked by At

I am trying to remove leading NA's when finding a moving average

I know in R that I can calculate a rolling average (of the 5 prior data points) using filter,

x <- 1:20
filter(x, c(0,rep(1/5,5)), sides = 1)

[1] NA NA NA NA NA  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17

What I would like would be an equivalent of this:

 [1]  0.0  1.0  1.5  2.0  2.5  3.0  4.0  5.0  6.0  7.0  8.0  9.0 10.0 11.0 12.0 13.0
[17] 14.0 15.0 16.0 17.0

where if the sequence is smaller than the window size it essentially only looks at the values that are in the window, and if the window size is 0, then it returns 0.

This is going to be used more as a weighted average of an indicator variable for example:

set.seed(02138)
x = replicate(20,sample(c(0,1),1))
filter(x, c(0,seq(5,1,-1)/15), sides = 1)

 [1]         NA         NA         NA         NA         NA 0.20000000 0.06666667
 [8] 0.00000000 0.00000000 0.33333333 0.26666667 0.53333333 0.73333333 0.53333333
[15] 0.33333333 0.20000000 0.40000000 0.26666667 0.53333333 0.73333333

while I would like it to output

 [1] 0.00000000 1.00000000 1.00000000 0.50000000 0.30000000 0.20000000 0.06666667
 [8] 0.00000000 0.00000000 0.33333333 0.26666667 0.53333333 0.73333333 0.53333333
[15] 0.33333333 0.20000000 0.40000000 0.26666667 0.53333333 0.73333333
0

There are 0 answers