【发布时间】:2018-10-28 19:56:14
【问题描述】:
这是this question的dplyr版本
我有以下data.table
initial.date <- as.POSIXct('2018-10-27 10:00:00',tz='GMT')
last.date <- as.POSIXct('2018-10-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
使用dplyr 最优雅、最快捷的方式是:
- 拆分:对于每一行定义在过去或未来最多 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
我想我的问题可以被问为“如何以与apply(df,1, function(x) df$column-x["column"]) 类似的方式修复dplyr 中的一行
我有使用dplyr 的潜在解决方案,但到目前为止一切都很慢。
【问题讨论】: