Created
July 26, 2018 07:57
-
-
Save coolbutuseless/c86555c1adbc118c352ab61e5923ab2e to your computer and use it in GitHub Desktop.
capturing expressions and evaluating later
This file contains hidden or 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) | |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
# 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