我正在使用data.table并且我想做一个非 equi 左连接/合并。
我有一张汽车价格表和另一张表来确定每辆车所属的汽车类别:
data_priceclass <- data.table()
data_priceclass$price_from <- c(0, 0, 200000, 250000, 300000, 350000, 425000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000, 1300000, 1400000, 1500000, 1600000, 1700000, 1800000)
data_priceclass$price_to <- c(199999, 199999, 249999, 299999, 349999, 424999, 499999, 599999, 699999, 799999, 899999, 999999, 1099999, 1199999, 1299999, 1399999, 1499999, 1599999, 1699999, 1799999, 1899999)
data_priceclass$price_class <- c(1:20, 99)
我使用非 equi 连接来合并这两个表。但是 x[y]-join 语法data.table删除了重复项。
cars <- data.table(car_price = c(190000, 500000))
cars[data_priceclass, on = c("car_price >= price_from",
"car_price < price_to"),
price_class := i.price_class,]
cars
请注意,值为 190000 的汽车应该在data_priceclass表中的两行上得到匹配,但是由于 x[y] 删除了重复项,因此我在输出中看不到这一点。通常,当我加入时,我总是使用merge函数而不是 x[y],因为我在使用 x[y] 时会失去控制。
但以下不适用于非 equi 连接:
merge(cars, data_priceclass,
by = c("car_price >= price_from",
"car_price < price_to"),
all.x = T , all.y = F)
任何提示如何使用不删除重复项的 data.table 进行非 equi 连接?