You might want to modify your grepl() based solution a bit, because right now it will apply the "Board" filter if that string is found anywhere in a school name — it's not exclusive to the specific string "Board". This may or may not matter given your list of school names, but in principle it would be better to modify that regular expression so that it actually represents your intention. Contrived example:
library(tidyverse)
df <- data.frame(
School = c("School A", "School B", "School C", "School D", "Boarding School"),
N = c(123, 245, 333, 298, 321)
)
# This could have unintended consequences
to_be <- function(df, group){
if(grepl(pattern = "Board", x = group))
df
else (dplyr::filter(df, School == group))
}
df %>% to_be("School A")
#> School N
#> 1 School A 123
df %>% to_be("Boarding School")
#> School N
#> 1 School A 123
#> 2 School B 245
#> 3 School C 333
#> 4 School D 298
#> 5 Boarding School 321
# Use a more precise regular expression
to_be2 <- function(df, group){
if(grepl(pattern = "^Board$", x = group))
df
else (dplyr::filter(df, School == group))
}
df %>% to_be2("School A")
#> School N
#> 1 School A 123
df %>% to_be2("Boarding School")
#> School N
#> 1 Boarding School 321
df %>% to_be2("Board")
#> School N
#> 1 School A 123
#> 2 School B 245
#> 3 School C 333
#> 4 School D 298
#> 5 Boarding School 321
While we're tossing out solutions, I might do something like this:
filter_for <- function(data, group) {
schools <- unique(data$School)
group <- switch(EXPR = group,
"Board" = schools,
group)
data %>%
dplyr::filter(School %in% group)
}
df %>% filter_for("School A")
#> School N
#> 1 School A 123
df %>% filter_for("Board")
#> School N
#> 1 School A 123
#> 2 School B 245
#> 3 School C 333
#> 4 School D 298
#> 5 Boarding School 321