gpt4 book ai didi

R:unequi join 与合并功能

转载 作者:行者123 更新时间:2023-12-03 16:19:10 24 4
gpt4 key购买 nike

我正在与 data.table 一起工作我想做一个非平等的左加入/合并。
我有一张包含汽车价格的表格和另一张表格来确定每辆车属于哪个汽车类别:

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)
我使用非对等连接来合并两个表。但是 data.table 的 x[y]-join 语法删除重复项。
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] 时我失去了控制。
但以下不适用于非等连接:
merge(cars, data_priceclass,
by = c("car_price >= price_from",
"car_price < price_to"),
all.x = T , all.y = F)
任何提示如何与 data.table 进行不删除重复项的非对等连接?

最佳答案

如评论中所述,cars 上的左连接是通过使用 cars 完成的作为子集条件iDT[i,j,by]句法。
这把 cars在右侧,与 SQL 相比,这可能违反直觉,我发现了这个 tutorial比较两种语法很有用。

cars <- data.table(car_price = c(190000, 500000))
data_priceclass[cars, .(car_price,x.price_from,x.price_to,price_class),on = .(price_from <= car_price,price_to > car_price)]

car_price x.price_from x.price_to price_class
1: 190000 0e+00 199999 1
2: 190000 0e+00 199999 2
3: 500000 5e+05 599999 8

如果你提高汽车价格:
cars <- cars * 10
data_priceclass[cars, .(car_price,x.price_from,x.price_to,price_class),on = .(price_from <= car_price,price_to > car_price)]

car_price x.price_from x.price_to price_class
1: 1900000 NA NA NA
2: 5000000 NA NA NA

关于R:unequi join 与合并功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67174277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com