在 R 中做 运行 求和时合并两个 data.tables

Merging two data.tables while doing running sum in R

我有一个data.table代表一家公司从2019年到2021年支付的股息。

library(data.table)
div_dt <- structure(list(pay_date = structure(c(18885L, 18793L, 18701L, 
18611L, 18520L, 18428L, 18337L, 18246L, 18155L, 18064L, 17910L
), class = c("IDate", "Date")), cash_amount = c(0.09, 0.09, 0.09, 
0.09, 0.08, 0.07, 0.07, 0.05, 0.04, 0.04, 0.07)), row.names = c(NA, 
-11L), class = c("data.table", "data.frame"))

下面的 table 显示了该股票在 2019 年至 2021 年之间的所有日历日。

calendar_dt = data.table(current_date = seq(min(div_dt$pay_date), max(div_dt$pay_date), by="days"))

我想显示这只股票在任何给定日期过去 4 个季度支付的股息总和。 为了解决这个问题,我在 calendar_dt 中添加了一个新列 div_start_date,它显示了必须将股息添加到给定日期 current_date.

的开始日期表格
calendar_dt[, div_start_date := date - 365]

谁能告诉我如何合并这些 table,以便在 calendar_dt 的每个日历日,过去 4 个季度的股息总和显示在一个新列中?

我们将不胜感激单行且内存高效的解决方案。

这会起作用(不是最有效的连接,但会完成工作)

# set keys
setkey(calendar_dt, current_date)
setkey(div_dt, pay_date)
# join
calendar_dt[calendar_dt, 
            cast_last_365 := div_dt[pay_date %between% c(current_date - 365, current_date), 
                                    sum(cash_amount)],
            by = .EACHI]