I want to compute a rolling weighted mean per group for a data.table like this:
DT <- data.table(group = rep(c(1,2), each = 5), value = 1:10, weight = 11:20)
group value weight
1: 1 1 11
2: 1 2 12
3: 1 3 13
4: 1 4 14
5: 1 5 15
6: 2 6 16
7: 2 7 17
8: 2 8 18
9: 2 9 19
10: 2 10 20
I found a working solution with the runner
package in this question Rolling over function with 2 vector arguments:
my_weighted_mean <- function(data) {
weighted.mean(data[, 1], w = data[, 2])
}
DT[, weighted_mean := runner::runner(x = .SD, f = my_weighted_mean , k = 3, na_pad = TRUE), .SDcols = c("value", "weight"), by = list(group)]
But the code is quite slow.
I guess it should work with frollapply
but the following doesn't, because I don't understand how to use frollapply with a two column function:
DT[, weighted_mean := frollapply(value, FUN = weighted.mean, n = 3, w = weights), by = list(group)]
Looking for a better performance (and a solution without runner)