2015-02-24 49 views
3

我想知道是否有任何有效的方法來過濾data.table中定義的多個條件的data.table。在這種情況下有2個data.table:如何通過另一個data.table中定義的多個條件過濾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循環。我不知道如何以其他方式重寫它。

+0

什麼是組?請標註「A,B,C」。 'B!= dt_filter [...'這裏不一樣,是錯字嗎? – Vlo 2015-02-24 20:31:22

+0

@Vlo列A是組ID。 – YYY 2015-02-24 20:34:06

+3

你的代碼真的很難閱讀。嘗試清理和簡化,爲我們和你的! – 2015-02-24 20:37:29

回答

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 
1

兩個其他的解決方案,閱讀更清晰,並且不需要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) ,]

+0

由於data.table默認使用「with」,我相信你可以進一步簡化爲: 'dt1 [which(A == dt_filter $ A&B!= dt_filter $ B),]]' – 2018-02-28 17:24:27

相關問題