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
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]
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]