Moving average with varying time window in R

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

    @thelatemail has done a great job, but he had an error in the code (test[] should be replaced with x[] inside the function) and more importantly he had to do the same thing for the end of the vector (if you want side=2). Also the window size should be twice+1 of the ith element in the vector (and n-ith element at the end). so, here is the final version:

    movavg.grow = function(x,window) {
      startma = sapply(1:(floor(window/2)),function(y) mean(x[1:((y-1)*2+1)]))
      endma = sapply(1:(floor(window/2)),function(y) mean(x[(length(x)-((y-1)*2)):length(x)]))
      endma = rev(endma)
      c(startma,
        filter(x,rep(1/window,window))[(floor(window/2):(length(x)- floor(window)/2)+1)],
        endma)
    }
    

    As for a test, what you want must return 1:10 for x=1:10

    > x=1:10
    > x
     [1]  1  2  3  4  5  6  7  8  9 10
    > movavg.grow(x,5)
     [1]  1  2  3  4  5  6  7  8  9 10
    > movavg.grow(x,3)
     [1]  1  2  3  4  5  6  7  8  9 10
    

提交回复
热议问题