首页 > 解决方案 > 使用 data.table 从起点和增量创建序列

问题描述

我想使用 data.table 重复向起点添加增量。

library(data.table)
dat <- data.table(time=seq(from=as.POSIXct("2018-01-01 01:00:01"),to=as.POSIXct("2018-01-01 01:00:10"), by="secs"), int=c(2,3,3,1,10,10,10,10,10,10), x=2*1:10)

> dat
                  time inc  x
 1: 2018-01-01 01:00:01   2  2
 2: 2018-01-01 01:00:02   3  4
 3: 2018-01-01 01:00:03   3  6
 4: 2018-01-01 01:00:04   1  8
 5: 2018-01-01 01:00:05  10 10
 6: 2018-01-01 01:00:06  10 12
 7: 2018-01-01 01:00:07  10 14
 8: 2018-01-01 01:00:08  10 16
 9: 2018-01-01 01:00:09  10 18
10: 2018-01-01 01:00:10  10 20

也就是说,从第 1 行开始,我想添加 to 的值inctime产生一个新时间。然后我需要添加inc那个新时间的值,以第三次到达。结果将是

> res
                  time inc  x
1: 2018-01-01 01:00:00   2  2
2: 2018-01-01 01:00:02   3  6
3: 2018-01-01 01:00:05  10 12

我可能知道如何循环执行此操作,但我想知道 data.table 是否也可以处理这些问题。

由于中的值time是连续的,我的想法是使用的累积值inc来索引,沿着线

index <- dat[...,cumsum(...inc...),...]
dat[index]

但我不能cumsum()忽略兴趣点之间的值。也许这可以在idata.table 的一部分中完成,但我不知道如何。任何人的想法?

标签: rdata.tablesequencecumulative-sum

解决方案


# start with finding the next time
dat[, next.time := time + int][!dat, on = .(next.time = time), next.time := NA]

# do this in a loop for the actual problem, and stop when final column is all NA
dat[dat, on = .(next.time = time), t1 := i.next.time]
dat[dat, on = .(t1 = time), t2 := i.next.time]

dat
#                   time int  x           next.time                  t1   t2
# 1: 2018-01-01 01:00:01   2  2 2018-01-01 01:00:03 2018-01-01 01:00:06 <NA>
# 2: 2018-01-01 01:00:02   3  4 2018-01-01 01:00:05                <NA> <NA>
# 3: 2018-01-01 01:00:03   3  6 2018-01-01 01:00:06                <NA> <NA>
# 4: 2018-01-01 01:00:04   1  8 2018-01-01 01:00:05                <NA> <NA>
# 5: 2018-01-01 01:00:05  10 10                <NA>                <NA> <NA>
# 6: 2018-01-01 01:00:06  10 12                <NA>                <NA> <NA>
# 7: 2018-01-01 01:00:07  10 14                <NA>                <NA> <NA>
# 8: 2018-01-01 01:00:08  10 16                <NA>                <NA> <NA>
# 9: 2018-01-01 01:00:09  10 18                <NA>                <NA> <NA>
#10: 2018-01-01 01:00:10  10 20                <NA>                <NA> <NA>

推荐阅读