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

标签 r data.table dplyr

我想知道是否有任何有效的方法可以通过另一个 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)

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

最佳答案

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

关于r - 如何通过另一个 data.table 中定义的多个条件过滤 data.table 中的案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28705305/

相关文章:

r - 将冒号运算符或破折号从字符强制转换为 r 中单元格内的向量

html - 在 R markdown 网站页面上包含横幅图像

r - 差异时间的分组平均值在 data.table 中失败

将长数据框 reshape 为宽数据框并使用一列作为前缀重命名新列

r - 按两个变量组汇总

javascript - Shiny.onInputChange 不是函数

r - 如何使用 R 设置条件 LaTeX 代码?

R data.table 分配单行列表类型列

R - 为什么向数据表添加 1 列几乎会使使用的峰值内存增加一倍?

r - 将 dplyr 函数映射到 R 数据帧中变量对的每个组合