How to calculate 7-day moving average in R?

后端 未结 3 2051
情歌与酒
情歌与酒 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 11:15

    ?rollmean says:

    character specifying whether the index of the result should be left- or right-aligned or centered (default) compared to the rolling window of observations.

    Let's look at a few different examples. I'll use rollmax, since it's results are a little easier/faster to see than (say) rollmean. Also, since I think padding helps the visualization, I'll include fill=NA, ensuring that all returns are the same length as the input. Lastly, I'll rbind them for vertical alignment.

    set.seed(4)
    vec <- sample(100, size = 15)
    

    In the first window of width 5, it looks at the values between 59 and 79. The max is 79, and with align="left", it places the result in the far left of the original vector's placement.

    rbind(vec) # illustrative
    #      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
    # vec    59    1   29   27   79   25   69   85   88     7    68    26     9    84    36
    ###      ^^^^^^^^^^^^^^^^^^^^^^ numbers considered in first window
    ###                          ^^ results go in this position when align="right"
    ###                ^^ results go in this position when align="center"
    ###      ^^ results go in this position when align="left"
    

    So looking at all three, notice where the 79 goes ... and where the NA pad.

    rbind(
      vec = vec,
      left = rollmax(vec, k=5, align="left", fill=NA),
      center = rollmax(vec, k=5, align="center", fill=NA),
      right = rollmax(vec, k=5, align="right", fill=NA)
    )
    #        [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] [,15]
    # vec      59    1   29   27   79   25   69   85   88     7    68    26     9    84    36
    # left     79   79   79   85   88   88   88   88   88    84    84    NA    NA    NA    NA
    # center   NA   NA   79   79   79   85   88   88   88    88    88    84    84    NA    NA
    # right    NA   NA   NA   NA   79   79   79   85   88    88    88    88    88    84    84
    

提交回复
热议问题