如何通过另一个data.table中定义的多个条件筛选data.table中的案例

6

我想知道是否有一种有效的方法来通过另一个数据表中定义的多个条件筛选数据表。在这种情况下,有两个数据表:

# the filter data.table defines the condition
dt_filter<-data.table(A=c(1,2),B=c(8,7))
# dt1 the data.table to be filtered
dt1<-data.table(A=rep(c(1,2),5),B=c(8,4,3,1,1,5,9,7,1,1),C=c(rep(1,5),rep(2,5)))

ls_tmp<-lapply (1:nrow(dt_filter),function(i){
# exclude the record with the A&B defined the filter
dt1_add<-dt1[A==dt_filter[[i,1]]&B!=dt_filter[[i,2]]]
})
result<- rbindlist(ls_tmp)

看起来我的示例不够高效,因为使用了lapply循环。我不确定如何通过其他方式重新编写它。


什么是group?请标记为A,B,CB!= dt_filter [.... 这里的不等于是打错了吗? - Vlo
@Vlo 列A是组ID。 - YYY
3
你的代码非常难以阅读。为了我们和你自己的好处,请尝试清理和简化它! - Señor O
@Señor O,对不起。它们已经被编辑过了。 - YYY
我可以建议您查看data.table的vignette以及data.table手册吗? - DJJ
显示剩余6条评论
2个回答

6
setkey(dt1, A)

dt1[dt_filter, allow = T][B != i.B, !'i.B']
#   A B C
#1: 1 1 1
#2: 1 1 2
#3: 1 3 1
#4: 1 9 2
#5: 2 1 1
#6: 2 1 2
#7: 2 4 1
#8: 2 5 2

5

还有两种更加清晰易读的解决方案,不需要使用 setkey

dt1[ which(dt1$A == dt_filter$A & dt1$B != dt_filter$B) ,]

现在使用 %in%

dt1[dt1$A %in% dt_filter$A & !(dt1$B %in% dt_filter$B) ,]


3
因为data.table默认使用"with",所以我认为你可以进一步简化为: dt1[ which(A == dt_filter$A & B != dt_filter$B), ] - Mark Egge

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接