如何通过另一个data.table中定义的多个条件过滤data.table中的案例 [英] How to filter cases in a data.table by multiple conditions defined in another data.table

查看:66
本文介绍了如何通过另一个data.table中定义的多个条件过滤data.table中的案例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何有效的方法可以通过另一个data.table中定义的多个条件来过滤data.table。在这种情况下,有两个data.table:

I wondered whether there is any efficient way to filter a data.table by multiple conditions defined in another data.table. There are 2 data.table in this case:

# 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循环而效率不高。我不确定如何用其他方式重写它。

It seems my sample is not efficient because of lapply loop. I am not sure how to re-write it by some other way.

推荐答案

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

这篇关于如何通过另一个data.table中定义的多个条件过滤data.table中的案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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