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

YYY*_*YYY 4 r dplyr data.table

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

# 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)
Run Code Online (Sandbox Code Playgroud)

由于lapply循环,我的样本似乎效率不高.我不知道如何通过其他方式重写它.

edd*_*ddi 5

setkey(dt1, A)

dt1[dt_filter, allow = T][B != i.B, !'i.B', with = F]
#   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
Run Code Online (Sandbox Code Playgroud)


raf*_*ira 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) ,]

  • 由于 data.table 默认使用“with”,我相信您可以进一步简化为: `dt1[ which(A == dt_filter$A &amp; B != dt_filter$B) , ]` (3认同)