
Last chance! 50% off unlimited learning
Sale ends in
eval_tidy()
is a variant of base::eval()
that powers the tidy
evaluation framework. Like eval()
it accepts user data as
argument. If supplied, it evaluates its input expr
in a data
mask. In additon eval_tidy()
supports:
Quosures. The expression wrapped in the quosure
evaluates in its original context (masked by data
if supplied).
Pronouns. If data
is supplied, the .env
and .data
pronouns are installed in the data mask. .env
is a reference to
the calling environment and .data
refers to the data
argument.
These pronouns lets you be explicit about where to find
values and throw errors if you try to access non-existent values.
eval_tidy(expr, data = NULL, env = caller_env())
An expression to evaluate.
A data frame, or named list or vector. Alternatively, a
data mask created with as_data_mask()
or new_data_mask()
.
The environment in which to evaluate expr
. This
environment is always ignored when evaluating quosures. Quosures
are evaluated in their own environment.
eval_tidy()
is stable.
quasiquotation for the second leg of the tidy evaluation framework.
# NOT RUN {
# With simple quoted expressions eval_tidy() works the same way as
# eval():
apple <- "apple"
kiwi <- "kiwi"
expr <- quote(paste(apple, kiwi))
expr
eval(expr)
eval_tidy(expr)
# Both accept a data mask as argument:
data <- list(apple = "CARROT", kiwi = "TOMATO")
eval(expr, data)
eval_tidy(expr, data)
# In addition eval_tidy() has support for quosures:
with_data <- function(data, expr) {
quo <- enquo(expr)
eval_tidy(quo, data)
}
with_data(NULL, apple)
with_data(data, apple)
with_data(data, list(apple, kiwi))
# Secondly eval_tidy() installs handy pronouns that allows users to
# be explicit about where to find symbols:
with_data(data, .data$apple)
with_data(data, .env$apple)
# Note that instead of using `.env` it is often equivalent and may
# be preferred to unquote a value. There are two differences. First
# unquoting happens earlier, when the quosure is created. Secondly,
# subsetting `.env` with the `$` operator may be brittle because
# `$` does not look through the parents of the environment.
#
# For instance using `.env$name` in a magrittr pipeline is an
# instance where this poses problem, because the magrittr pipe
# currently (as of v1.5.0) evaluates its operands in a *child* of
# the current environment (this child environment is where it
# defines the pronoun `.`).
# }
# NOT RUN {
data %>% with_data(!!kiwi) # "kiwi"
data %>% with_data(.env$kiwi) # NULL
# }
Run the code above in your browser using DataLab