I have the following data.table
initial.date <- as.POSIXct(\'2018-10-27 10:00:00\',tz=\'GMT\')
last.date <- as.POSIXct(\'2018-12-28 17:00:
This may work:
res <- res[1:5,]
res2 <- setDT(res)
res2 <- res2[, `:=` (min_60 = datetime - 60, plus_60 = datetime + 60, idx = .I)][
res2, on = .(InstrumentSymbol = InstrumentSymbol, datetime >= min_60, datetime <= plus_60), allow.cartesian = TRUE][
idx != i.idx, .SD[which.min(abs(i.TradePrice - TradePrice))], by = id][
, .(id, minpricewithin60 = i.TradePrice, index.minpricewithin60 = i.idx)][
res, on = .(id)][, `:=` (min_60 = NULL, plus_60 = NULL, idx = NULL)]
res2[]
id minpricewithin60 index.minpricewithin60 PriorityDateTime TradePrice InstrumentSymbol datetime
1: 1 3 3 2018-10-27 10:00:00 1 asset1 2018-10-27 10:00:00
2: 2 4 4 2018-10-27 10:00:30 2 asset2 2018-10-27 10:00:30
3: 3 1 1 2018-10-27 10:01:00 3 asset1 2018-10-27 10:01:00
4: 4 2 2 2018-10-27 10:01:30 4 asset2 2018-10-27 10:01:30
5: 5 3 3 2018-10-27 10:02:00 5 asset1 2018-10-27 10:02:00