我想检查一个条件,如果col为=='value'-那么从列列表中是否有任何列=='value2'
# create dummy data set
pb=c('1','0','0','0','0','1','Not_ans','1','0','Not_ans')
qa=c('1','1','0','0','1','0','Not_ans','1','Not_ans','Not_ans')
#zy=c('1','Not_ans','0','1','Not_ans','0','1','1','1','Not_ans')
#sub questions for pb
pb.abr=c('1','0','0','0','0','1','0','1','0','0')
pb.ras=c('0','0','0','0','1','0','0','1','0','0')
pb.sfg=c('1','0','0','0','0','0','0','1','0','0')
#sub questions for qa
qa.fgs=c('1','0','0','0','0','0','0','1','0','0')
qa.sdf=c('0','1','0','0','0','0','0','0','0','0')
qa.tyu=c('0','0','0','0','1','0','0','1','0','0')
df=data.frame(pb,qa,pb.abr,pb.ras,pb.sfg,qa.fgs,qa.sdf,qa.tyu)
df
pb qa pb.abr pb.ras pb.sfg qa.fgs qa.sdf qa.tyu
1 1 1 1 0 1 1 0 0
2 0 1 0 0 0 0 1 0
3 0 0 0 0 0 0 0 0
4 0 0 0 0 0 0 0 0
5 0 1 0 1 0 0 0 1
6 1 0 1 0 0 0 0 0
7 Not_ans Not_ans 0 0 0 0 0 0
8 1 1 1 1 1 1 0 1
9 0 Not_ans 0 0 0 0 0 0
10 Not_ans Not_ans 0 0 0 0 0 0
在上述数据集中的-我要检查的是列'pb'是否为0,然后是否有任何列pb.abr或pb.ras或pb.sfg == 1
subset_df=subset(df,(pb==0) & ((pb.abr==1) | (pb.ras==1)|(pb.sfg==1)))
挑战是我有100列pb.xxx格式的列,而手动将所有列写为子集不是可行的解决方案。如何使用使用contains("pb.")
的逻辑检查上述内容,并在列之间使用OR
条件检查列,最后提供数据帧?
答案 0 :(得分:2)
我们可以使用filter_at
library(dplyr)
df %>%
filter(pb == 0) %>%
filter_at(vars(matches("pb\\.")), any_vars(. == 1))
# pb qa pb.abr pb.ras pb.sfg qa.fgs qa.sdf qa.tyu
#1 0 1 0 1 0 0 0 1
或在基数R
中df[df$pb == 0 & rowSums(df[grep("pb\\.", names(df))] == 1) > 0, ]
# pb qa pb.abr pb.ras pb.sfg qa.fgs qa.sdf qa.tyu
#5 0 1 0 1 0 0 0 1
答案 1 :(得分:0)
样本数据
dont' forget to set StringsAsFactors to FALSE!
df=data.frame(pb,qa,pb.abr,pb.ras,pb.sfg,qa.fgs,qa.sdf,qa.tyu, stringsAsFactors = FALSE)
代码
library(dplyr)
df %>%
#set all columns starting with 'pb.' to numeric
mutate_at( vars( starts_with("pb.") ), funs( as.numeric ) ) %>%
#first filter
filter( pb == "0" ) %>%
#second filter
filter( rowSums( .[, grep("pb\\.", names(df))]) > 0 )
输出
pb qa pb.abr pb.ras pb.sfg qa.fgs qa.sdf qa.tyu 1 0 1 0 1 0 0 0 1
答案 2 :(得分:0)
作为一个班轮:
filter(df,pb==0 & rowSums(z[,grepl("pb\\.",names(z))])>0)