【问题标题】:Subset in list of tuples (multiple columns) with %in% clause带有 %in% 子句的元组列表(多列)中的子集
【发布时间】:2018-12-11 12:41:10
【问题描述】:

我想使用来自另一个 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%不是正确的方法,你会如何解决这个问题?

【问题讨论】:

标签: r datatable tuples subset where


【解决方案1】:

您正在做的是为每行制作 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

【讨论】:

  • 嗨,伊曼纽尔。感谢您的小费。我刚刚意识到这种方法只会返回第一场比赛!试试这个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))) DT1[col1 == DT2$col1 &amp; col2 == DT2$col2],行 (2,4) 和 (3,5) 应该出现不止一次
  • 你是对的,我编辑了我的答案。这就是为什么在乞讨中提供可重复的示例有助于正确回答的原因。
  • 谢谢伊曼纽尔。原始示例非常庞大且繁琐,以至于我们无法检测到此错误。我认为只有当你真的在寻找它时,才能复制这样的异常。
  • 顺便说一句,对于我的 41 列、4500 万行和 17GB 大小的数据表来说,这种方法是不可持续的。有什么优化性能的建议吗?
猜你喜欢
  • 1970-01-01
  • 2014-09-17
  • 1970-01-01
  • 2010-10-31
  • 2017-11-26
  • 2012-10-13
  • 2011-02-15
  • 2011-03-07
相关资源
最近更新 更多