0

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))
neilfws
  • 32,751
  • 5
  • 50
  • 63
KCS
  • 67
  • 3

1 Answers1

2

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
neilfws
  • 32,751
  • 5
  • 50
  • 63
  • This is the correct way to solve this. See also here and try out `df1 %>% filter(across(starts_with("column"), ~grepl("Y", .)))` -> It won't work as expected or desired! – TarJae Jul 11 '22 at 05:20