I understand how I can filter my data by one or by many conditions. How can I apply the same conditional filter to multiple variables? If I have just one or two variables it is fine to copy and paste, but in my real data I have 25 variables I need to apply my filter to.
library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
#> Warning: package 'readr' was built under R version 4.1.2
# target criteria
target <- c("b", "d") %>% paste(collapse = "|")
target
#> [1] "b|d"
# my data
my_data <- tribble(
~col1, ~col2, ~col3, ~col4, ~col5,
"aaa", "aaa", "aaa", "aaa", "eee",
"aaa", "bbb", "bbb", "bbb", "eee",
"bbb", "ccc", "ccc", "ccc", "eee",
"aaa", "ddd", "ddd", "ddd", "eee",
"aaa", "eee", "eee", "eee", "ddd",
"aaa", "fff", "fff", "fff", "eee"
)
# filter becomes vulerable to copy and paste errors if I have many variables
my_filtered_data <- my_data %>%
filter(str_detect(col1, target) |
str_detect(col3, target) |
str_detect(col5, target))
my_filtered_data
#> # A tibble: 4 x 5
#> col1 col2 col3 col4 col5
#> <chr> <chr> <chr> <chr> <chr>
#> 1 aaa bbb bbb bbb eee
#> 2 bbb ccc ccc ccc eee
#> 3 aaa ddd ddd ddd eee
#> 4 aaa eee eee eee ddd
Created on 2021-12-28 by the reprex package (v2.0.1)