Using zoo
for example using the data.table
package:
library(zoo)
library(data.table)
DT <- data.table(z)
DT[, roll_x := rollmeanr(x, 3, fill = NA), y]
Of course if have some missing values it is better to use rollapplyr
:
DT[, roll_x := rollapplyr(x, 3, mean, fill = NA), y]
Another package that is going to be faster is caTools
:
library(caTools)
DT[, roll_x := runmean(x, 3, align = 'right', endrule = 'NA'), by = y]
In terms of data frames this works too:
transform(z, roll_x = ave(x, y, FUN = function(x) rollmeanr(x, 3, fill = NA)))