Skip to content

Instantly share code, notes, and snippets.

@turgeonmaxime
Created March 4, 2019 18:09
Show Gist options
  • Save turgeonmaxime/4495977976829ecfd22348b94b5fbf1d to your computer and use it in GitHub Desktop.
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.
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