Trying to get (reverse) cumulative sums in a moving window by group in data.table. For example, from the following data I'd like to get those values in the "roll_cumsum" column:
dt = data.table()
dt[, a := seq(1, 10, 1)]
dt[, group := rep(1:2, each = 5)]
dt[, roll_cumsum := c(15, 14, 12, 9, 5, 40, 34, 27, 19, 10)]
I got the results I wanted with the code below but it's quite slow for a large dataset:
partial_sum = function(x) { n <- seq_along(x); cumsum(x)[length(x)] - cumsum(x)[n] + x[n] }
dt[, partial_sum(a), by = group]
Any suggestions to make the calculation faster? Thank you so much!