According to this threat I learned, rolling sums for variable b in the following data.table can be achieved as follows:
data creation + computing rolling sums:
x <- data.table(a = sample(letters[1:3], 100, replace = TRUE), b = runif(100))
setorder(x, a)
# alternative 1
x[, .(b, Reduce(`+`, shift(b, 0:2))), by = a]
# alternative 2
x[, .(b, stats::filter(b, rep(1, 3), sides = 1)), by = a]
Current + desired output:
a b V2 V2_desired
1: a 0.457665568 NA 0.457665568
2: a 0.752555834 NA 1.210221
3: a 0.864672124 2.0748935 2.0748935
4: a 0.542168656 2.1593966 2.1593966
5: a 0.197962875 1.6048037 1.6048037
Now there are NAs generated for the first two obs. in each by group. I need to adjust one of the alternatives to sum only the current obs. (last two obs.) in cases where the group index starts (is at position 2). This should be generalizable such that I could consider windows of last n values and the exceptions are handled.
Any idea?