Created
March 4, 2019 18:09
-
-
Save turgeonmaxime/4495977976829ecfd22348b94b5fbf1d to your computer and use it in GitHub Desktop.
For a Shiny app: filter data based on user input. We don't know how many filtering variables will be used.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
# What I want | |
target <- mtcars %>% | |
filter(cyl %in% c(4, 8), | |
gear %in% c(3, 4)) | |
# Solution | |
dynamic_filter <- function(df, variables, conditions){ | |
filter_conditions <- purrr::map2(variables, conditions, | |
function(var, cond) { | |
# Construct list of quoted filtering conditions | |
rlang::quo(!!sym(var) %in% cond) | |
}) | |
dplyr::filter(df, !!!filter_conditions) | |
} | |
var1 <- "cyl" | |
var2 <- "gear" | |
values1 <- c(4, 8) | |
values2 <- c(3, 4) | |
mtcars %>% | |
dynamic_filter(list(var1, var2), list(values1, values2)) %>% | |
identical(target) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment