Generating a moving sum variable in R

后端 未结 3 2048
盖世英雄少女心
盖世英雄少女心 2021-02-09 07:16

I suspect this is a somewhat simple question with multiple solutions, but I\'m still a bit of a novice in R and an exhaustive search didn\'t yield answers that spoke well to wha

3条回答
  •  轮回少年
    2021-02-09 08:00

    you can also use filter of standard packages (stats) to do moving sum:

    ms=function(x,n=5) as.numeric(stats::filter(x,rep(1, n),method="convolution",sides=1))
    x=c(1,2,3,4,5,6,7,8,9)
    ms(x,5)
    NA NA NA NA 15 20 25 30 35
    

    To do a 1-lag, insert NA at the begining and take the number of elements (or lines):

    ms.1lag=c(NA,ms(x,5))[1:length(x)]
    cbind(x,ms.1lag)
    x ms.1lag
    [1,] 1      NA
    [2,] 2      NA
    [3,] 3      NA
    [4,] 4      NA
    [5,] 5      NA
    [6,] 6      15
    [7,] 7      20
    [8,] 8      25
    [9,] 9      30
    

    If you use this frequently,

    ms=function(x,n=5,lag=0)
      c(rep(NA,lag),
        as.numeric(stats::filter(x,rep(1, n),method="convolution",sides=1)))[1:length(x)]
    cbind(x,ms5.1=ms(x,5,1))
          x ms5.1
     [1,] 1    NA
     [2,] 2    NA
     [3,] 3    NA
     [4,] 4    NA
     [5,] 5    NA
     [6,] 6    15
     [7,] 7    20
     [8,] 8    25
     [9,] 9    30
    

提交回复
热议问题