Rolling / moving avg by group

前端 未结 2 600
醉话见心
醉话见心 2021-01-12 15:51

How to generate rolling mean with grouped data. Here\'s the data

set.seed(31)
dd<-matrix(sample(seq(1:20),30,replace=TRUE),ncol=3)

Add

2条回答
  •  误落风尘
    2021-01-12 16:41

    Using data.table and caTools

    library(data.table)
    library(caTools)
    DT <- data.table(d, key='du')
    DT[, lapply(.SD, function(y) 
           runmean(y, 3, alg='fast',align='right')), by=du]
    

    Update

    If you want to create new columns in the existing dataset

     nm1 <- paste0('V', 2:4)
     nm2 <- paste0("V", 4:6)
     DT[, (nm1):=lapply(.SD, as.numeric), .SDcols=nm1][,
          (nm2):=lapply(.SD, function(y) runmean(y, 3, alg='fast',
                                 align='right')), by=du]
    

提交回复
热议问题