r - How do I take a rolling product using data.table -
dt <- data.table(x=c(1, .9, .8, .75, .5, .1)) dt x 1: 1.00 2: 0.90 3: 0.80 4: 0.75 5: 0.50 6: 0.10
for each row, how product of x row , next 2 rows?
x prod.3 1: 1.00 0.7200 2: 0.90 0.5400 3: 0.80 0.3000 4: 0.75 0.0375 5: 0.50 na 6: 0.10 na
more generally, each row, how product of x row , next n rows?
you can try
library(zoo) rollapply(dt, 3, fun = prod) x [1,] 0.7200 [2,] 0.5400 [3,] 0.3000 [4,] 0.0375
to match expected output
dt[, prod.3 :=rollapply(x, 3, fun=prod, fill=na, align='left')]
Comments
Post a Comment