I have a data set where I want to perform rolling functions over a date range.
I have currently done this via a loop, where I subset the main data for each range, then do the calculations and piece it together. It works well but the actual data set is over 2M rows and it took over 15 minutes to complete.
library(data.table)
start_date <- as.Date(fast_strptime("2021-03-04", "%Y-%m-%d"))
end_date <- start_date + 2
output <- data.table(NULL)
d = structure(list(date = structure(c(18690, 18690, 18692, 18692, 18692, 18693, 18693, 18694, 18695, 18695, 18695), class = "Date"),
id = c(1, 2, 1, 1, 2, 3, 1, 4, 4, 2, 1),
w = c(3, 1, 1, 1, 4, 2, 1, 2, 3, 4, 1)),
row.names = c(NA, -16L), class = c("data.table", "data.frame"))
while (end_date < Sys.Date()) {
x <- d[date >= start_date & date <= end_date, .(tw = sum(w)),
by = .(id)]
setorder(x, -tw, id)
x[, wprop := {x = sum(tw); y = cumsum(tw) / x}]
x[, idprop := {x = uniqueN(id); y = 1:.N / x}]
start_date <- end_date + 1
end_date <- start_date + 2
x[, start_date := start_date]
x[, end_date := end_date]
output <- rbindlist(list(output, x))
}
I would prefer a data.table solution since I will be doing this for a few different time windows so I need it to be as fast as possible.