【问题标题】:Merging two data.tables while doing running sum in R在 R 中运行求和时合并两个 data.tables
【发布时间】:2021-12-20 03:59:06
【问题描述】:

我有一个 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"))

下表显示了该股票在 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]

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

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

【问题讨论】:

    标签: r data.table


    【解决方案1】:

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

    # 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]
    

    【讨论】:

    • 无需加入,以下对我来说效果很好。 calendar_dt[, cast_last_365 := div_dt[pay_date %between% c(current_date - 365, current_date), sum(cash_amount)], by = .EACHI]
    猜你喜欢
    • 2015-11-29
    • 2021-07-29
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2019-05-13
    • 2017-06-29
    • 2019-03-17
    相关资源
    最近更新 更多