【发布时间】:2018-10-28 15:38:21
【问题描述】:
我有以下data.table
initial.date <- as.POSIXct('2018-10-27 10:00:00',tz='GMT')
last.date <- as.POSIXct('2018-12-28 17:00:00',tz='GMT')
PriorityDateTime=seq.POSIXt(from=initial.date,to = last.date,by = '30 sec')
TradePrice=seq(from=1, to=length(PriorityDateTime),by = 1)
ndf<- data.frame(PriorityDateTime,TradePrice)
ndf$InstrumentSymbol <- rep_len(x = c('asset1','asset2'),length.out = length(ndf$PriorityDateTime))
ndf$id <- seq(1:length(x = ndf$InstrumentSymbol))
ndf$datetime <- ymd_hms(ndf$PriorityDateTime)
res <- ndf %>% data.table()
看起来像这样:
> res
PriorityDateTime TradePrice InstrumentSymbol id datetime
1: 2018-10-27 10:00:00 1 asset1 1 2018-10-27 10:00:00
2: 2018-10-27 10:00:30 2 asset2 2 2018-10-27 10:00:30
3: 2018-10-27 10:01:00 3 asset1 3 2018-10-27 10:01:00
4: 2018-10-27 10:01:30 4 asset2 4 2018-10-27 10:01:30
5: 2018-10-27 10:02:00 5 asset1 5 2018-10-27 10:02:00
使用data.table 最优雅、最快捷的方式是:
- 拆分:对于每一行定义在过去或未来最多 60 秒(时间差小于 60 秒)具有
datetime的其他行,并且具有相同的InstrumentSymbol这条线的。 - 应用:在这些接近的行中,哪一个具有最接近该行的
TradePrice[i]的TradePrice:获取原始data.frame中的index和另一行的TradePrice - 组合:将结果作为新列重新组合到原始
data.table中,例如作为新列index.minpricewithin60和minpricewithin60
示例结果:
> res
PriorityDateTime TradePrice InstrumentSymbol id datetime minpricewithin60 index.minpricewithin60
1: 2018-10-27 10:00:00 1 asset1 1 2018-10-27 10:00:00 2 2
2: 2018-10-27 10:00:30 2 asset2 2 2018-10-27 10:00:30 4 4
3: 2018-10-27 10:01:00 3 asset1 3 2018-10-27 10:01:00 1 1
4: 2018-10-27 10:01:30 4 asset2 4 2018-10-27 10:01:30 2 2
5: 2018-10-27 10:02:00 5 asset1 5 2018-10-27 10:02:00 3 3
在base 中,我可以修复一行并将其用于条件。例如,如果我想获得第一个TradePrice,其中id 与该行的id 相同,我可以使用apply(df,1, function(x) df$TradePrice[which(df$id==x["id"])[1]])。您能否解释一下data.table 的连接(例如)如何实现相同的效果?
编辑:数据现在更大,我可以在不到 2.5 分钟的时间内在我的体面 PC(i7 4750 2B,12GB RAM)上运行的任何答案都将被考虑。干杯。
【问题讨论】:
标签: r data.table