How to calculate 7-day moving average in R?

后端 未结 3 2054
情歌与酒
情歌与酒 2021-01-27 10:27

I\'m using the rollmean function of zoo package to calculate a simple 7-day moving average. The function has an argument align and if I pu

3条回答
  •  温柔的废话
    2021-01-27 10:55

    I think it is instructive to see the results of all 3 next to each other:

    library(zoo)
    means <- sapply(c("right","center","left"),
                    function(x)zoo::rollmean(test,7,align = x, na.pad = TRUE))
    cbind(test,means)
          test    right   center     left
     [1,]    6       NA       NA 19.28571
     [2,]   50       NA       NA 21.42857
     [3,]   11       NA       NA 15.28571
     [4,]   16       NA 19.28571 15.00000
     [5,]    1       NA 21.42857 19.42857
     [6,]   26       NA 15.28571 25.28571
     [7,]   25 19.28571 15.00000 22.71429
     [8,]   21 21.42857 19.42857 24.42857
     [9,]    7 15.28571 25.28571 22.00000
    [10,]    9 15.00000 22.71429 23.42857
    ...
    [40,]   41 27.28571 31.85714 33.57143
    [41,]   49 29.42857 31.71429 33.85714
    [42,]   35 33.71429 31.42857 30.00000
    [43,]   20 31.85714 33.57143 26.85714
    [44,]   44 31.71429 33.85714 25.42857
    [45,]   28 31.42857 30.00000       NA
    [46,]   18 33.57143 26.85714       NA
    [47,]   43 33.85714 25.42857       NA
    [48,]   22 30.00000       NA       NA
    [49,]   13 26.85714       NA       NA
    [50,]   10 25.42857       NA       NA
    

提交回复
热议问题