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

查看:64
本文介绍了使用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(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天全站免登陆