【发布时间】:2017-09-22 00:03:08
【问题描述】:
我有一个数据框,dat:
dat<-data.frame(col1=rep(1:4,3),
col2=rep(letters[24:26],4),
col3=letters[1:12])
我想仅使用数据框filter 中的行给出的组合在两个不同的列上过滤dat:
filter<-data.frame(col1=1:3,col2=NA)
lists<-list(list("x","y"),list("y","z"),list("x","z"))
filter$col2<-lists
因此,例如,将选择包含 (1,x) 和 (1,y) 的行,但不会选择 (1,z)、(2,x) 或 (3,y)。
我知道如何使用 for 循环:
#create a frame to drop results in
results<-dat[1,]
for(f in 1:nrow(filter)){
temp_filter<-filter[f,]
temp_dat<-dat[dat$col1==temp_filter[1,1] &
dat$col2%in%unlist(temp_filter[1,2]),]
results<-rbind(results,temp_dat)
}
或者如果你更喜欢 dplyr 风格:
require(dplyr)
results<-dat[0,]
for(f in 1:nrow(filter)){
temp_filter<-filter[f,]
temp_dat<-filter(dat,col1==temp_filter[1,1] &
col2%in%unlist(temp_filter[1,2])
results<-rbind(results,temp_dat)
}
结果应该返回
col1 col2 col3
1 1 x a
5 1 y e
2 2 y b
6 2 z f
3 3 z c
7 3 x g
我通常会使用合并进行过滤,但我现在不能,因为我必须根据列表而不是单个值检查 col2。 for 循环有效,但我认为会有更有效的方法来执行此操作,可能使用apply 或do.call 的一些变体。
【问题讨论】: