I found this old post Finding rows containing a value (or values) in any column
library(dplyr)
df <- data.frame(
col1 = sample(c('M017', 'M018', 'M019', 'M20', 'Other'), 20, replace = TRUE),
col2 = sample(c('m017', 'm018', 'm019', 'm20', 'Other'), 20, replace = TRUE),
col3 = sample(c('AM017', 'BM018', 'CM019', 'DM20', 'Other'), 20, replace = TRUE),
stringsAsFactors = FALSE
)
I want to change this such that:
- it selects all columns with rows LIKE ‘M017’, ‘M018’
- it does not select rows LIKE ‘M019’, ‘M20’
I often get confused how to do this … I get confused between str_detect and grepl.
For example:
df_filtered <- df %>%
filter(if_any(everything(), ~ grepl('M017|M018', ., ignore.case = TRUE))) %>%
filter(!if_any(everything(), ~ grepl('M019|M20', ., ignore.case = TRUE)))
df_filtered <- df %>%
filter_all(any_vars(grepl('M017|M018', ., ignore.case = TRUE))) %>%
filter_all(all_vars(!grepl('M019|M20', ., ignore.case = TRUE)))
Is there a correct way to do this?
New contributor
farrow90 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.