Moving average with varying time window in R

后端 未结 6 1637
时光取名叫无心
时光取名叫无心 2020-12-31 23:43

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

6条回答
  •  死守一世寂寞
    2021-01-01 00:11

    Let me jump on the rollapply train, too:

    > rollapply(c(NA, NA, x), width=3, FUN=mean, na.rm=T)
    [1] 3.000000 6.000000 4.666667 6.333333 4.666667 6.000000 5.000000 6.333333
    

    Prepending two = 3-1 NA values and using na.rm=T has the effect of extending the time series but ignoring the new values for calculating the mean. A slightly more difficult but otherwise equivalent syntax

    > rollapply(c(NA, NA, x), width=3, FUN=function(v) mean(v, na.rm=T))
    

    Thanks to Matthew for pointing this out.

提交回复
热议问题