Filtering an exact character match in multiple columns

Viewed 85

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

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

How can I do this across multiple columns?

1 Answers

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"))
Related