Reputation: 65
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
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