Sliding window in R

前端 未结 2 451
轮回少年
轮回少年 2020-12-18 10:36

I have a dataframe DF, with two columns A and B shown below:

A                    B                  
1                    0             
3                           


        
相关标签:
2条回答
  • 2020-12-18 10:45

    The R library TTR has a number of functions for calculating averages over sliding windows

    SMA = simple moving average

    data$sma <- SMA(data$B, 3)
    

    More documentation is here http://cran.r-project.org/web/packages/TTR/TTR.pdf

    0 讨论(0)
  • 2020-12-18 11:08

    Try this:

    # form input data
    library(zoo)
    B <- c(0, 0, 0, 1, 0, 1, 1, 1, 0)
    
    # calculate
    k <- 3
    rollapply(B, 2*k-1, function(x) max(rollmean(x, k)), partial = TRUE)
    

    The last line returns:

    [1] 0.0000000 0.3333333 0.3333333 0.6666667 0.6666667 1.0000000 1.0000000
    [8] 1.0000000 0.6666667
    

    If there are NA values you might want to try this:

    k <- 3
    B <- c(1, 0, 1, 0, NA, 1)
    rollapply(B, 2*k-1, function(x) max(rollapply(x, k, mean, na.rm = TRUE)), partial = TRUE)
    

    where the last line gives this:

    [1] 0.6666667 0.6666667 0.6666667 0.5000000 0.5000000 0.5000000
    

    Expanding it out these are formed as:

    c(mean(B[1:3], na.rm = TRUE), ##
    max(mean(B[1:3], na.rm = TRUE), mean(B[2:4], na.rm = TRUE)), ##
    max(mean(B[1:3], na.rm = TRUE), mean(B[2:4], na.rm = TRUE), mean(B[3:5], na.rm = TRUE)),
    max(mean(B[2:4], na.rm = TRUE), mean(B[3:5], na.rm = TRUE), mean(B[4:6], na.rm = TRUE)),
    max(mean(B[3:5], na.rm = TRUE), mean(B[4:6], na.rm = TRUE)), ##
    mean(B[4:6], na.rm = TRUE)) ##
    

    If you don't want the k-1 components at each end (marked with ## above) drop partial = TRUE.

    0 讨论(0)
提交回复
热议问题