data.table中的滚动连接不会提供所需的输出

时间:2017-12-08 12:08:09

标签: r data.table

我的data.table(dt)有3列(“times”,“name”,“price”)。我的目标是在输入数字和时间值时找到价格。但是,当我输入一个不在dt中的时间时,我想得到它的下一个(或最后一个)价格。 我这样做,但它似乎没有工作,因为我得到NA如果价格不在dt。

library(data.table)
dt <- data.table(
times = c("2017-02-13 07:02:45","2017-02-13 07:02:48","2017-02-13 07:02:49"),
name = c("name1", "name1", "name1"),
price = c(10,15,20)
)

setkey(dt, times, name)

nm = "name1"
tt = "2017-02-13 07:02:46"
dt[times == tt & name == nm]

pricelookup <- function(tt, nm, data = dt) {
dt[J(tt, nm), roll = TRUE][, price]
}
pricelookup(tt,nm)

1 个答案:

答案 0 :(得分:2)

也许非equi连接更好。使用:

dt[CJ(tt, nm), on = .(times <= V1, name = V2)]

给出:

                 times  name price
1: 2017-02-13 07:02:46 name1    10

在你的功能中:

pricelookup <- function(tt, nm, data = dt) {
  dt[CJ(tt, nm), on = .(times <= V1, name = V2)][, price]
}

现在将提供正确的输出:

> pricelookup(tt, nm)
[1] 10

如果您只想要连接的第一个结果,请将mult = 'first'添加到连接操作。要查看它的作用,请比较以下两个连接的输出:

> dt[CJ(tt, nm), on = .(times >= V1, name = V2)]
                 times  name price
1: 2017-02-13 07:02:46 name1    15
2: 2017-02-13 07:02:46 name1    20

> dt[CJ(tt, nm), on = .(times >= V1, name = V2), mult = 'first']
                 times  name price
1: 2017-02-13 07:02:46 name1    15

使用过的数据:

dt <- data.table(
  times = as.POSIXct(c("2017-02-13 07:02:45","2017-02-13 07:02:48","2017-02-13 07:02:49"), format = "%Y-%m-%d %H:%M:%S"),
  name = c("name1", "name1", "name1"),
  price = c(10,15,20)
)

setkey(dt, times, name)

nm = "name1"
tt = as.POSIXct("2017-02-13 07:02:46", format = "%Y-%m-%d %H:%M:%S")