P_aza
P_aza

Reputation: 147

Filtering an exact character match in multiple columns

I am using dplyr to filter columns that contain "Yes"

df %>%
  filter(col1 == "Yes")

How can I do this across multiple columns?

Upvotes: 3

Views: 1110

Answers (1)

akrun
akrun

Reputation: 887048

We may use if_any (to subset rows where any of the columns have the "Yes") or if_all (only subset rows where all the columns in the selected columns have 'Yes' in that row)

library(dplyr)
df1 %>%
   filter(if_any(everything(), ~ .x == "Yes"))

everything() selects all the columns. If we need to apply only on a subset of columns, use either a character vector of column names or index i.e.

df1 %>%
    filter(if_all(c(col1, col2), ~ .x == "Yes"))

Upvotes: 5

Related Questions