Skip to content

Instantly share code, notes, and snippets.

@coolbutuseless
Created July 26, 2018 07:57
Show Gist options
  • Save coolbutuseless/c86555c1adbc118c352ab61e5923ab2e to your computer and use it in GitHub Desktop.
Save coolbutuseless/c86555c1adbc118c352ab61e5923ab2e to your computer and use it in GitHub Desktop.
capturing expressions and evaluating later
library(tidyverse)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Base R styel
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
filter_base <- function(df, boolean_expression) {
# Don't evaluate what we were given. Just hold it.
captured_expression <- substitute(boolean_expression)
# with df as the environment, now evaluate the expression
keep_rows <- with(df, eval(captured_expression))
# use those values for whatever
df[keep_rows, ]
}
filter_base(mtcars, cyl==8)
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Tidyverse/rlang/quasiquotation style
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
filter_tidy <- function(df, boolean_expression) {
# Don't evaluate what we were given. Just hold it.
captured_expression <- enquo(boolean_expression)
# evaluate it within a function that is aware of the quasiquotation stuff
filter(df, !!captured_expression)
}
filter_tidy(mtcars, cyl==8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment