KCS
KCS

Reputation: 65

grepl() to filter using two columns

I am trying to filter in R with grepl() if "Y" is present in a row in either column 1 and/or column 2. I tried this code and it did not work.

filter(grepl("Y", column1|column2))

Upvotes: 0

Views: 1611

Answers (1)

neilfws
neilfws

Reputation: 33782

You can use if_any, along with a selector for the columns. For example:

library(dplyr)

df1 <- data.frame(column1 = c("Y", "N", "N"), 
                  column2 = c("N", "Y", "N"))

df1 %>% 
  filter(if_any(all_of(c("column1", "column2")), ~grepl("Y", .)))

or

df1 %>% 
  filter(if_any(starts_with("column"), ~grepl("Y", .)))

Result in both cases:

  column1 column2
1       Y       N
2       N       Y

Upvotes: 1

Related Questions