Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

r - How to filter cases in a data.table by multiple conditions defined in another 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)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...