How to rollapply over a multi column data table

后端 未结 2 1200
心在旅途
心在旅途 2021-01-15 01:20

I would like to use the rollapply function over a multi column datatable, namely I would like to be able to use each column independantly for instance let\'s consider the fo

相关标签:
2条回答
  • 2021-01-15 01:21

    You are almost there and can do:

    lapply(DT[,2:3], function(x) rollapply(x,width=3, FUN=mean))
    #$y
    #[1] 3.333333 3.333333 3.333333 3.333333 3.333333 3.333333 3.333333
    
    #$v
    #[1] 2 3 4 5 6 7 8
    
    0 讨论(0)
  • 2021-01-15 01:21

    Just to add another option using data.table only

    library(data.table) # v1.9.6+
    

    Define the rolling mean function

    rollMean <- function(x, n) Reduce(`+`, shift(x, 0L:(n - 1L)))/n
    

    Apply it on multiple columns while specifying .SDcols

    DT[, lapply(.SD, rollMean, 3L), .SDcols = y:v]
    #           y  v
    # 1:       NA NA
    # 2:       NA NA
    # 3: 3.333333  2
    # 4: 3.333333  3
    # 5: 3.333333  4
    # 6: 3.333333  5
    # 7: 3.333333  6
    # 8: 3.333333  7
    # 9: 3.333333  8
    
    0 讨论(0)
提交回复
热议问题