How to calculate 7-day moving average in R?

后端 未结 3 2158
情歌与酒
情歌与酒 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:53

    align has the same meaning in rollmean and rollapply but it is easier to see in rollapply since using input data 1:8 and a window width of 3 and using toString rather than mean as the function to apply we can show which indexes are used at each point.

    The alignment refers to which edge (or center) of the window is aligned with the current point as we iterate through successive positions of the input.

    Thus using a window of length 3 it uses the value at the current position and the prior 2 positions for align = "right". For example, for the first position of the input 1:8 there is not a window of 3 values whose right end is at the first position so we get an NA. For the second position of the input there are only 2 positions to that point so again there is not a window of 3 positions whose right end is at the current position and so once again we get NA. For the third position there are three positions ending in position 3 so we pass c(1, 2, 3) to toString which formats them as seen below. For the 4th position there are again 3 positions whose right end is at position 4 so we get 2, 3, 4 and so on as shown on the first line marked ## in the code below.

    For align = "center" it places the center of the window at the current position so it uses the prior value, current value and next value.

    For align = "left" it places the left end of the window at the current position so it uses the current value and the next 2 values.

    library(zoo)
    x <- 1:8
    
    rollapply(x, 3, toString, align = "right", fill = NA)
    ## [1] NA        NA        "1, 2, 3" "2, 3, 4" "3, 4, 5" "4, 5, 6" "5, 6, 7" "6, 7, 8"
    
    rollapply(x, 3, toString, align = "center", fill = NA)
    ## [1] NA        "1, 2, 3" "2, 3, 4" "3, 4, 5" "4, 5, 6" "5, 6, 7" "6, 7, 8" NA       
    
    rollapply(x, 3, toString, align = "left", fill = NA)
    ## [1] "1, 2, 3" "2, 3, 4" "3, 4, 5" "4, 5, 6" "5, 6, 7" "6, 7, 8" NA        NA      
    

    Note that align = "center" is the default if align= is not specified and there are wrappers, rollmeanr and rollapplyr (note r on the end), which default to align = "right".

提交回复
热议问题