r - 使用 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 的值inc
,time
产生一个新时间。然后我需要添加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()
忽略兴趣点之间的值。也许这可以在i
data.table 的一部分中完成,但我不知道如何。任何人的想法?
解决方案
# 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>
推荐阅读
- python - 如果不存在,则在 Python 中使用 gremlin 添加边缘
- javascript - 有什么方法可以在 Shopify Liquid 模板中使用 Cookie?
- flutter - 我应该在 Flutter 中为 i18n 使用什么:S.of(context) 或 S.current?
- python - 未找到自定义 python 包
- php - 将配置变量传递给 Eloquent 模型
- python - function to determine the frequency of a sinusoid
- swift - 使用 PDFKit 提取 PDF 亮点
- ruby-on-rails - 如何从 Rails 中的文本装置生成 db/seed.rb 文件
- amazon-web-services - AWS 策略基于服务限制权限
- javascript - 使用 for 循环在 Class Constructor 中创建 x 数量的新对象,然后在 JavaScript 中修改它们