带有 %in% 子句的元组列表(多列)中的子集

Subset in list of tuples (multiple columns) with %in% clause

我想使用来自另一个 data.table 的元组列表(多列)对 data.table 进行子集化,但不确定如何。

使用单列进行子集化

DT1[col1 %in% DT2(col_1)]

我试过的是

DT1[c(col1, col2) %in% DT2(col_1, col_2)]

虽然没有成功。错误是

i evaluates to a logical vector length 91369852 but there are 45684926
rows. Recycling of logical i is no longer allowed as it hides more
bugs than is worth the rare convenience. Explicitly use
rep(...,length=.N) if you really need to recycle.

有什么想法吗?如果%in%不是正确的方法,你会如何解决这个问题?

你正在做的是为每一行生成 2 个布尔值,所以你有这个错误并且没有执行你的操作。所以确实 %in% 不是这样做的方法。

你应该用 and:

把它变成双重条件

我做了一个可重现的例子:

DT1 = as.data.table(data.frame(col1 = c(1,2,3,2,5,1,3,3,1,2), 
                               col2 = c(3,4,5,4,3,4,5,3,4,5), 
                               col3 = c(1,2,3,4,5,6,7,8,9,10))) 

DT2 = as.data.table(data.frame(col1 = c(1,2,1,2,3,4,3,2,4,3), 
                               col2 = c(3,4,5,3,6,4,5,4,3,4), 
                               col3=c(11,12,13,14,15,16,17,18,19,20)))

编辑:根据评论我更正了我的答案(这比我想象的要多)。

我创建了一个过滤函数,它可以帮助我检查 DT2 中是否有任何匹配项

filter <- function(x){
  any(x[1] == DT2[["col1"]] & x[2] == DT2[["col2"]])
}

我在 DT1 的每一行上应用这个函数

indexes = apply(DT1, 1, filter)

我过滤

> DT1[indexes, ]
   col1 col2 col3
1:    1    3    1
2:    2    4    2
3:    3    5    3
4:    2    4    4
5:    3    5    7