David Denton
Sep 8, 2018 · 1 min read

Another possibility, if you want to keep the variables and conditions separate.

filter_by2 <- function(df, variables, conditions){
filter_conditions <- purrr::map2(variables, conditions, function(var, cond) rlang::quo((!!(as.name(var))) %in% !!cond))
dplyr::filter(df, !!!filter_conditions)
}

test2 <- filter_by2(mtcars, variables = list(‘cyl’, ‘vs’), conditions = list(c(6,4), 1))

This approach makes it harder to use filters that aren’t just simple %in% statements. You could add an operator argument (<, >, !=, ==) to the function and paste the filter conditions together. Then you could perform “greater than” or “less than” filtering on continuous variables.

    David Denton

    Written by