使用 data.table 执行半连接 [英] Perform a semi-join with data.table

查看:21
本文介绍了使用 data.table 执行半连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何执行 半连接与data.table?半连接类似于内连接,只是它只返回 X 的列(而不是 Y 的列),并且不重复 X 的行以匹配 Y 的行.例如,以下代码执行内连接加入:

How do I perform a semi-join with data.table? A semi-join is like an inner join except that it only returns the columns of X (not also those of Y), and does not repeat the rows of X to match the rows of Y. For example, the following code performs an inner join:

x <- data.table(x = 1:2, y = c("a", "b"))
setkey(x, x)
y <- data.table(x = c(1, 1), z = 10:11)

x[y]
#   x y  z
# 1: 1 a 10
# 2: 1 a 11

半连接只会返回 x[1]

推荐答案

更多可能性:

w = unique(x[y,which=TRUE])  # the row numbers in x which have a match from y
x[w]

如果 x 中有重复的键值,则需要:

If there are duplicate key values in x, then that needs :

w = unique(x[y,which=TRUE,allow.cartesian=TRUE])
x[w]

或者,反过来:

setkey(y,x)
w = !is.na(y[x,which=TRUE,mult="first"])
x[w]

如果 nrow(x) <<nrow(y) 那么 y[x] 方法应该更快.
如果 nrow(x) >> nrow(y) 那么 x[y] 方法应该更快.

If nrow(x) << nrow(y) then the y[x] approach should be faster.
If nrow(x) >> nrow(y) then the x[y] approach should be faster.

但反反加入也很有吸引力:-)

But the anti anti join appeals too :-)

这篇关于使用 data.table 执行半连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆