I am trying to use rollmean from the package zoo in a data.table while grouping data.
It works fine when all groups have enough data:
library(data.table)
dt = data.table(x=rep(c("a","b"),10),y=rnorm(20))
dt[,.(ma=rollmean(y, k = 7, fill=NA,align="right")), by = .(x)]
But when one of the groups has too little data, it returns an error
dt2 = data.table(x=rep(c("c"),1),y=rnorm(1))
dt3=rbind(dt,dt2)
dt3[,.(ma=rollmean(y, k = 7, fill=NA,align="right")), by = .(x)]
Here's the error message:
Column 1 of result for group 3 is type 'logical' but expecting type 'double'. Column types must be consistent for each group.
It seems to happen because rollmean returns a logical (a mix of TRUE and NA) when it doesn't have enough data
Given that my data is always positive I use the following trick to make my code run anyway
dt4=dt3[,.(ma=rollmean(y, k = 7, fill=-1,align="right")), by = .(x)]
dt4[ma==-1,ma:=NA]
dt4
Is there a proper/better way to do it?