使用R中的data.table计算两个日期之间的累积和

时间:2016-01-12 19:49:33

标签: r date data.table cumulative-sum

我的data.table形状如下:

date_from    date_until    value
2015-01-01   2015-01-03    100    
2015-01-02   2015-01-05     50
2015-01-02   2015-01-04     10
...

我想要做的是:我想计算一年中每个日期的累计金额。对于第一行,值100将与2015-01-01至2015-01-03的每一天相关。我想添加与特定日期相关的所有值。

所以,最后会有data.table这样:

date        value
2015-01-01  100
2015-01-02  160
2015-01-03  160
2015-01-04   60
2015-01-05   50

data.table有没有简单的方法可以做到这一点?

1 个答案:

答案 0 :(得分:4)

dt[, .(date = seq(as.Date(date_from, '%Y-%m-%d'),
                  as.Date(date_until, '%Y-%m-%d'),
                  by='1 day'),
       value), by = 1:nrow(dt)][, sum(value), by = date]
#         date  V1
#1: 2015-01-01 100
#2: 2015-01-02 160
#3: 2015-01-03 160
#4: 2015-01-04  60
#5: 2015-01-05  50

使用foverlaps的其他选项:

# convert to Date for ease
dt[, date_from := as.Date(date_from, '%Y-%m-%d')]
dt[, date_until := as.Date(date_until, '%Y-%m-%d')]

# all of the dates
alldates = dt[, do.call(seq, c(as.list(range(c(date_from, date_until))), by = '1 day'))]

# foverlaps to find the intersections
foverlaps(dt, data.table(date_from = alldates, date_until = alldates,
                         key = c('date_from', 'date_until')))[,
          sum(value), by = date_from]
#    date_from  V1
#1: 2015-01-01 100
#2: 2015-01-02 160
#3: 2015-01-03 160
#4: 2015-01-04  60
#5: 2015-01-05  50