Filter by testing logical condition across multiple columns
We can do this with filter_at
and any_vars
df %>%
filter_at(vars(matches("^Var")), any_vars(.> 100))
# Demo1 Demo2 Condition Var1 Var2 Var3
#1 9 14 A 76 101 5
#2 10 15 B 105 23 5
Or using base R
, create a logical expression with lapply
and Reduce
and subset the rows
df[Reduce(`|`, lapply(df[grepl("^Var", names(df))], `>`, 100)),]
In base-R
one can write the same filter using rowSums
as:
df[rowSums((df[,grepl("^Var",names(df))] > 100)) >= 1, ]
# Demo1 Demo2 Condition Var1 Var2 Var3
# 2 9 14 A 76 101 5
# 3 10 15 B 105 23 5