gpt4 book ai didi

r - R 中复杂的非等值合并

转载 作者:行者123 更新时间:2023-12-01 22:19:04 24 4
gpt4 key购买 nike

我正在尝试在两个表之间进行复杂的非等值连接。我受到了上次 useR2016 ( https://channel9.msdn.com/events/useR-international-R-User-conference/useR2016/Efficient-in-memory-non-equi-joins-using-datatable ) 中的演示的启发,这让我相信这将是 data.table 的合适任务。我的表 1 如下所示:

library(data.table)
sp <- c("SAB","SAB","SAB","SAB","EPN","EPN","BOP","BOP","BOP","BOP","BOP","PET","PET","PET")
dbh <- c(10,12,16,22,12,16,10,12,14,20,26,12,16,18)
dt1 <- data.table(sp,dbh)
dt1
sp dbh
1: SAB 10
2: SAB 12
3: SAB 16
4: SAB 22
5: EPN 12
6: EPN 16
7: BOP 10
8: BOP 12
9: BOP 14
10: BOP 20
11: BOP 26
12: PET 12
13: PET 16
14: PET 18

这是树木及其胸径的列表。我的第二个表(如下)给出了一个通用表,其中为每个树种提供了一个胸径范围,以对树的大小类别进行分类:

gr_sp <- c("RES","RES","RES","RES","RES","RES", "DEC", "DEC", "DEC", "DEC", "DEC", "DEC")
sp <- c("SAB","SAB", "SAB", "EPN", "EPN", "EPN", "BOP", "BOP", "BOP", "PET", "PET", "PET")
dbh_min <- c(10, 16, 22, 10, 14, 20, 10, 18, 24, 10, 20, 26)
dbh_max <- c(14, 20, 30, 12, 18, 30, 16, 22, 30, 18, 24, 30)
dhb_clas <- c("s", "m", "l", "s", "m", "l", "s", "m", "l", "s", "m", "l")

dt2 <- data.table(gr_sp, sp, dbh_min, dbh_max, dhb_clas)
dt2
gr_sp sp dbh_min dbh_max dhb_clas
1: RES SAB 10 14 s
2: RES SAB 16 20 m
3: RES SAB 22 30 l
4: RES EPN 10 12 s
5: RES EPN 14 18 m
6: RES EPN 20 30 l
7: DEC BOP 10 16 s
8: DEC BOP 18 22 m
9: DEC BOP 24 30 l
10: DEC PET 10 18 s
11: DEC PET 20 24 m
12: DEC PET 26 30 l

我希望我的最终表是按物种(“sp”字段)连接的两个表,并且在“DBH_MIN”和“DBH_MAX”规定的 dhb 范围内。这将使我的表格看起来像:

data.table(dt1, gr_sp = c("RES","RES","RES","RES","RES","RES","DEC","DEC","DEC","DEC","DEC","DEC","DEC","DEC"), dhb_clas = c("s","s","m","l","s","m","s","s","s","m","l","s","s","s"))
sp dbh gr_sp dhb_clas
1: SAB 10 RES s
2: SAB 12 RES s
3: SAB 16 RES m
4: SAB 22 RES l
5: EPN 12 RES s
6: EPN 16 RES m
7: BOP 10 DEC s
8: BOP 12 DEC s
9: BOP 14 DEC s
10: BOP 20 DEC m
11: BOP 26 DEC l
12: PET 12 DEC s
13: PET 16 DEC s
14: PET 18 DEC s

我尝试过类似的方法:

dt1[dt2, on=.(sp=sp, dbh>=dbh_min, dbh<=dbh_max)]

这给出了太多行...

感谢您的帮助

最佳答案

所以我非常接近。我遇到了 2 个问题,首先是 data.table 包 ( Data table error could not find function "." ) 的错误安装导致了一个模糊的错误。

解决这个问题后,我更仔细地发现:

dt1[dt2, on=.(sp=sp, dbh>=dbh_min, dbh<=dbh_max), nomatch=0]

用一个糟糕的 dbh 列给了我我想要的东西。反转命令:

dt2[dt1, on=.(sp=sp, dbh_min<=dbh, dbh_max>=dbh)]

仅用一个无用的额外列解决了问题。

关于r - R 中复杂的非等值合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41043047/

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