gpt4 book ai didi

r - 明确地选择 data.table 中与另一个 data.table 中的行匹配的行

转载 作者:行者123 更新时间:2023-12-04 16:04:56 25 4
gpt4 key购买 nike

给定两个数据表( tbl_Atbl_B ),我想选择 tbl_A 中的所有行在 tbl_B 中有匹配的行, 和 我希望代码富有表现力 .如果%in%运算符是为 data.tables 定义的,这样的东西是理想的:

subset <- tbl_A[tbl_A %in% tbl_B]

我可以想到很多方法来完成我想要的事情,例如:
# double negation (set differences)
subset <- tbl_A[!tbl_A[!tbl_B,1,keyby=a]]

# nomatch with keyby and this annoying `[,V1:=NULL]` bit
subset <- tbl_B[,1,keyby=.(a=x)][,V1:=NULL][tbl_A,nomatch=0L]

# nomatch with !duplicated() and setnames()
subset <- tbl_B[!duplicated(tbl_B),.(x)][tbl_A,nomatch=0L]; setnames(subset,"x","a")

# nomatch with !unique() and setnames()
subset <- unique(tbl_B)[,.(x)][tbl_A,nomatch=0L]; setnames(subset,"x","a")

# use of a temporary variable (Thanks @Frank)
subset <- tbl_A[, found := FALSE][tbl_B, found := TRUE][(found)][,found:=NULL][]

但是每个表达式都很难阅读,乍一看代码在做什么并不明显。有没有更惯用/表达方式来完成这项任务?

举例来说,这里有一些玩具 data.tables:
# toy tables
tbl_A <- data.table(a=letters[1:5],
b=1:5,
c=rnorm(5))
tbl_B <- data.table(x=letters[3:7],
y=13:17,
z=rnorm(5))
# both tables might have multiple rows with the same key fields.
tbl_A <- rbind(tbl_A,tbl_A)
tbl_B <- rbind(tbl_B,tbl_B)
setkey(tbl_A,a)
setkey(tbl_B,x)

以及包含 tbl_A 中的行的预期结果匹配 tbl_B 中的至少一行:
   a b          c
1: c 3 -0.5403072
2: c 3 -0.5403072
3: d 4 -1.3353621
4: d 4 -1.3353621
5: e 5 1.1811730
6: e 5 1.1811730

最佳答案

添加另外 2 个选项

tbl_A[fintersect(tbl_A[,.(a)], tbl_B[,.(a=x)])]


tbl_A[unique(tbl_A[tbl_B, nomatch=0L, which=TRUE])]

关于r - 明确地选择 data.table 中与另一个 data.table 中的行匹配的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49181690/

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