100% found this document useful (1 vote)
142 views2 pages

Tidy Evaluation With Rlang::: Cheat Sheet

Tidy Evaluation (Tidy Eval) is a framework for doing non-standard evaluation that makes it easier to program with tidyverse functions. It involves quoting expressions to be evaluated later in specific environments using quosures or quoted expressions. Quosures store both quoted code and the environment, allowing predictable evaluation, while quoted expressions only store code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
142 views2 pages

Tidy Evaluation With Rlang::: Cheat Sheet

Tidy Evaluation (Tidy Eval) is a framework for doing non-standard evaluation that makes it easier to program with tidyverse functions. It involves quoting expressions to be evaluated later in specific environments using quosures or quoted expressions. Quosures store both quoted code and the environment, allowing predictable evaluation, while quoted expressions only store code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Tidy evaluation with rlang : : CHEAT SHEET

Vocabulary Quoting Code a+b e


Quote code in one of two ways (if in doubt use a quosure): 3 a+b
Tidy Evaluation (Tidy Eval) is not a package, but a framework
for doing non-standard evaluation (i.e. delayed evaluation) that
makes it easier to program with tidyverse functions.
QUOSURES EXPRESSION
pi Symbol - a name that represents a value Quosure- An expression that has Quoted Expression - An expression
or object stored in R. is_symbol(expr(pi)) a
b been saved with an environment ? that has been saved by itself.
(aka a closure). A quoted expression can be evaluated
Environment - a list-like object that binds q when a+b e when a+b
A quosure can be evaluated later later to return a result that will depend
symbols (names) to objects stored in memory. a + b, a b evaluated 3 in the stored environment to a+b evaluated ? on the environment it is evaluated in
a 1
Each env contains a link to a second, parent
b 2 return a predictable result.
env, which creates a chain, or search path, of
environments. is_environment(current_env())

rlang::caller_env(n = 1) Returns rlang::quo(expr) Quote contents as a quosure. Also quos to quote rlang::expr(expr) Quote contents. Also exprs to quote multiple
calling env of the function it is in. multiple expressions. a <- 1; b <- 2; q <- quo(a + b); qs <- quos(a, b) expressions. a <- 1; b <- 2; e <- expr(a + b); es <- exprs(a, b, a + b)

rlang::child_env(.parent, ...) Creates rlang::enquo(arg) Call from within a function to quote what the user rlang::enexpr(arg) Call from within a function to quote what the user
new env as child of .parent. Also env. passed to an argument as a quosure. Also enquos for multiple args. passed to an argument. Also enexprs to quote multiple arguments.
rlang::current_env() Returns quote_this < - function(x) enquo(x) quote_that < - function(x) enexpr(x)
execution env of the function it is in. quote_these < - function(…) enquos(…) quote_those < - function(…) enexprs(…)

Constant - a bare value (i.e. an atomic rlang::new_quosure(expr, env = caller_env()) Build a rlang::ensym(x) Call from within a function to quote what the user
1 quosure from a quoted expression and an environment. passed to an argument as a symbol, accepts strings. Also ensyms.
vector of length 1). is_bare_atomic(1)
new_quosure(expr(a + b), current_env()) quote_name < - function(name) ensym(name)
Call object - a vector of symbols/constants/calls quote_names < - function(…) ensyms(…)
abs ( 1 ) that begins with a function name, possibly
followed by arguments. is_call(expr(abs(1)))

pi code Code - a sequence of symbols/constants/calls Parsing and Deparsing Evaluation


that will return a result if evaluated. Code can be: To evaluate an expression, R :
3.14 result e
1. Evaluated immediately (Standard Eval) "a + b" "a + b" 1.Looks up the symbols in the expression in
parse a+b deparse a 1 the active environment (or a supplied one),
2. Quoted to use later (Non-Standard Eval)
followed by the environment's parents
is_expression(expr(pi)) + fun
Parse - Convert a string Deparse - Convert a saved b 2 2.Executes the calls in the expression
to a saved expression. expression to a string.
e Expression - an object that stores quoted code fun(1, 2) The result of an expression depends on
without evaluating it. is_expression(expr(a + b)) a+b
a+b 3 which environment it is evaluated in.
rlang::parse_expr(x) Convert rlang::expr_text(expr, width =
q Quosure- an object that stores both quoted a string to an expression. Also 60L, nlines = Inf) Convert expr
code (without evaluating it) and the code's parse_exprs, sym, parse_quo, to a string. Also quo_name. QUOTED EXPRESSION QUOSURES (and quoted exprs)
a + b, a b environment. is_quosure(quo(a + b)) parse_quos. e<-parse_expr("a+b") expr_text(e)
rlang::eval_bare(expr, env = rlang::eval_tidy(expr, data = NULL,
a rlang::quo_get_env(quo) Return parent.frame()) Evaluate expr in env = caller_env()) Evaluate expr in
b
the environment of a quosure. env. eval_bare(e, env =.GlobalEnv) env, using data as a data mask.
Will evaluate quosures in their
a
b rlang::quo_set_env(quo, expr)
Set the environment of a quosure. Building Calls a
stored environment. eval_tidy(q)
+b Data Mask - If data is non-NULL,
a + b rlang::quo_get_expr(quo) Return rlang::call2(.fn, ..., .ns = NULL) Create a call from a function and a list eval_tidy inserts data into the
the expression of a quosure. search path before env, matching
of args. Use exec to create and then evaluate the call. (See back page a+b
for !!!) args <- list(x = 4, base = 2) symbols to names in data.
Expression Vector - a list of pieces of quoted call2("log", x = 4, base = 2)
code created by base R's expression and parse log (x = 4 , base = 2 ) call2("log", !!!args) Use the pronoun .data$ to force a
functions. Not to be confused with expression. a <- 1; b <- 2 symbol to be matched in data, and
exec("log", x = 4, base = 2) p <- quo(.data$a + !!b) !! (see back) to force a symbol to
2 mask <- tibble(a = 5, b = 6)
exec("log", !!!args) eval_tidy(p, data = mask) be matched in the environments.

RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at tidyeval.tidyverse.org • rlang 0.3.0 • Updated: 2018-11
Quasiquotation (!!, !!!, :=) Programming Recipes WRITE A
FUNCTION
THAT RECOGNIZES
Quoting function- A function that quotes any of its arguments internally for delayed evaluation QUASIQUOTATION
QUOTATION QUASIQUOTATION in a chosen environment. You must take special steps to program safely with a quoting function. (!!,!!!,:=)
Storing an expression Quoting some parts of an
without evaluating it. expression while evaluating 1. Capture the
How to spot a quoting function? dplyr::filter(cars, speed = = 25) quasiquotation-aware
e <- expr(a + b) and then inserting the results argument with rlang::enquo.
of others (unquoting others). A function quotes an argument if the speed dist
e <- expr(a + b) argument returns an error when run
on its own. 1 25 85 2. Evaluate the arg with rlang::eval_tidy.
e
Many tidyverse functions are quoting add1 <- function(x) {
log ( e ) log(e) log ( a + b ) log(a + b) speed == 25 q <- rlang::enquo(x)
functions: e.g. filter, select, mutate, 1
fun a+b fun summarise, etc. Error! rlang::eval_tidy(q) + 1 2
}
expr(log(e)) expr(log(!!e))

PROGRAM WITH A QUOTING FUNCTION PASS MULTIPLE ARGUMENTS PASS TO ARGUMENT NAMES
rlang provides !!, !!!, and := for doing quasiquotation. TO A QUOTING FUNCTION OF A QUOTING FUNCTION
!!, !!!, and := are not functions but syntax (symbols recognized
data_mean <- function(data, var) { group_mean <- function(data, var, …) { named_mean <- function(data, var) {
by the functions they are passed to). Compare this to how
require(dplyr) require(dplyr) require(dplyr)
. is used by magrittr::%>%() var <- rlang::enquo(var) 1 var <- rlang::enquo(var) var <- rlang::ensym(var) 1
. is used by stats::lm() data %>% group_vars <- rlang::enquos(…) 1 data %>%
.x is used by purrr::map(), and so on. summarise(mean = mean(!!var)) 2 data %>% summarise(!!name := mean(!!var)) 2
} group_by(!!!group_vars) %>% 2 }
!!, !!!, and := are only recognized by some rlang functions and
functions that use those functions (such as tidyverse functions). summarise(mean = mean(!!var))
}

a !! Unquotes the 1. Capture user argument that will 1. Capture user arguments that will 1. Capture user argument that will
symbol or call that be quoted with rlang::enquo. be quoted with rlang::enquos. be quoted with rlang::ensym.
log ( 1 + b ) log(1 + b) follows. Pronounced
fun fun 2 "unquote" or "bang- 2. Unquote the user argument into 2. Unquote splice the user arguments 2. Unquote the name into the
!! the quoting function with !!. into the quoting function with !!!. quoting function with !! and :=.
bang." a <- 1; b <- 2
expr(log(!!a + b)) expr(log(!!a + b))

a+b Combine !! with ()


to unquote a longer
log ( 3 ) log(3) expression. MODIFY USER ARGUMENTS APPLY AN ARGUMENT TO A DATA FRAME PASS CRAN CHECK
fun a <- 1; b <- 2
!!
expr(log(!!(a + b)))
expr(log(!!(a + b)))
my_do <- function(f, v, df) { subset2 <- function(df, rows) { #' @importFrom rlang .data 1
!!! Unquotes a vector f <- rlang::enquo(f) 1 rows <- rlang::enquo(rows) 1 mutate_y <- function(df) {
x or list and splices the v <- rlang::enquo(v) vals <- rlang::eval_tidy(rows, data = df) dplyr::mutate(df, y = .data$a +1) 2
log ( 8, b = 2 ) log(8, b=2) results as arguments todo <- rlang::quo((!!f)(!!v)) 2 df[vals, , drop = FALSE] 2 }
fun into the surrounding rlang::eval_tidy(todo, df) }
!!! call. Pronounced 3
"unquote splice" or }
expr(log(!!!x))
"bang-bang-bang."
x <- list(8, b = 2)
expr(log(!!!x)) 1. Capture user arguments 1. Capture user argument Quoted arguments in tidyverse functions
with rlang::enquo. with rlang::enquo. can trigger an R CMD check NOTE about
n undefined global variables. To avoid this:
uno := := Replaces an = to 2. Unquote user arguments into a 2. Evaluate the argument with
1 uno = 1 allow unquoting within new expression or quosure to use rlang::eval_tidy. Pass the data 1. Import rlang::.data to your package,
1 the name that appears frame to data to use as a data mask. perhaps with the roxygen2 tag
!!
on the left hand side of 3. Evaluate the new expression/ @importFrom rlang .data
tibble::tibble(!!n := 1) the =. Use with !! quosure instead of the original 3. Suggest in your documentation
n <- expr(uno) argument that your users use the .data 2. Use the .data$ pronoun in front of
tibble::tibble(!!n := 1) and .env pronouns. variable names in tidyverse functions

RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at tidyeval.tidyverse.org • rlang 0.3.0 • Updated: 2018-11

You might also like