I want to compute a moving average over a certain time window without generating NAs at the beginning of the time series. For instance, if I set the time window to 3, the 2
A custom function in base R to get you there:
movavg.grow <- function(x,window,sides) {
startma <- sapply(1:(window-1),function(y) mean(x[1:y]))
c(startma,filter(x,rep(1/window,window),sides=sides)[window:length(x)])
}
Test it:
> test <- c(3,9,2,8,4,6,5,8)
> movavg.grow(x=test,window=3,sides=1)
[1] 3.000000 6.000000 4.666667 6.333333 4.666667 6.000000 5.000000 6.333333