【问题标题】:Conditional rolling sum有条件的滚动总和
【发布时间】:2016-10-31 20:22:09
【问题描述】:

这是数据框

Date        ID cost Value
15/12/2016   1  yes    200
15/10/2016   1  yes    100
15/9/2016    1  yes    55
15/04/2016   1  yes    1000
15/12/2016   2  yes    300
15/10/2016   2  yes    200
15/9/2016    2  yes    100
15/04/2016   2  yes    1000
15/12/2016   3  no     300
15/10/2016   3  no     200
15/9/2016    3  no     100
15/04/2016   3  no     1000

我想在每个 ID 的 cost =“yes”上重复 3 个月的滚动总和。请注意,在示例中 ID 仅为 3,但在我的数据库中为 n。

输出应该是

Date        ID  Value  Rolling_Sum
15/12/2016   1   200   355
15/10/2016   1   100   155
15/9/2016    1   55    55
15/04/2016   1   1000  1000
15/12/2016   2   300   600
15/10/2016   2   200   300
15/9/2016    2   100   100
15/04/2016   2   1000  1000

我在其他问题中看到了很多例子。我最大的问题之一是日期没有继续......所以我可以在不同的数据之间有不同的滞后。

谢谢

【问题讨论】:

  • 现在我正在尝试 rollapply 但我不知道是不是这样
  • 似乎,但这个问题有点不同和复杂.. 可以吗?

标签: r dataframe rolling-sum


【解决方案1】:

您可以为此使用data.table-package 中的foverlaps 函数:

library(data.table)
library(lubridate)

# convert the data to a 'data.table'
setDT(dt)
# convert the Date column to date-class
dt[, Date := as.Date(Date, '%d/%m/%Y')]
# create an exact same column to be used by the 'foverlaps' function
dt[, bdate := Date]
# create a reference 'data.table' with the 3 month intervals
dtc <- copy(dt)[, bdate := Date %m-% months(3)]
# set the keys for the reference data.table (needed for the 'foverlaps' function) 
setkey(dtc, ID, bdate, Date)
# create the overlaps and summarise
foverlaps(dt[cost=='yes'], dtc, type = 'within')[, .(val = sum(i.Value)), by = .(ID, Date)]

给出:

   ID       Date  val
1:  1 2016-12-15  355
2:  1 2016-10-15  155
3:  1 2016-09-15   55
4:  1 2016-04-15 1000
5:  2 2016-12-15  600
6:  2 2016-10-15  300
7:  2 2016-09-15  100
8:  2 2016-04-15 1000

【讨论】:

  • COOL 它有效,谢谢.. 但我不明白 bdate := Date %m-% months(3)。它是如何工作的?
  • @Tyu1990 bdate := Date %m-% months(3) 从每个日期减去 3 个月,参见 ?'%m+%'(加载 lubridate-package 时)。有关:= 的解释,请参阅data.table Getting started wiki 的page on reference sematics
  • 如果我在列条件中添加条件,它会给我这个警告:警告消息:1:在 difftime(e1, e2, units = "days") 中:达到 7856Mb 的总分配:请参阅帮助(memory.size) 2:在 difftime(e1, e2, units = "days") 中:达到 7856Mb 的总分配:参见帮助(memory.size)
  • @Tyu1990 无法重现。您可以发布一个新问题或在R-Public chat-room 中提问吗?
猜你喜欢
  • 2021-11-05
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多