Moving average with varying time window in R

后端 未结 6 1601
时光取名叫无心
时光取名叫无心 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

    Feature you are asking is called 'partial' window and AFAIK it is already available in zoo package.

    There is also new fast rolling mean function in data.table to be released in 1.12.0.
    Unfortunately it does not support partial window, but you can achieve desired behavior using 'adaptive' feature of that function in the following way:

    x = c(3,9,2,8,4,6,5,8)
    window = 3
    
    library(data.table)
    n = c(seq.int(window), rep(window, length(x)-window))
    frollmean(x, n, adaptive=TRUE)
    #[1] 3.000000 6.000000 4.666667 6.333333 4.666667 6.000000 5.000000 6.333333
    

    You can find manual entry for new function online at ?froll.

提交回复
热议问题