Evaluate a formula
f_eval.Rdf_eval_rhs evaluates the RHS of a formula and f_eval_lhs
evaluates the LHS. f_eval is a shortcut for f_eval_rhs since
that is what you most commonly need.
Arguments
- f
A formula. Any expressions wrapped in
uq()will will be "unquoted", i.e. they will be evaluated, and the results inserted back into the formula. Seef_interpfor more details.- data
A list (or data frame).
find_datais a generic used to find the data associated with a given object. If you want to makef_evalwork for your own objects, you can define a method for this generic.- x
An object for which you want to find associated data.
Details
If data is specified, variables will be looked for first in this
object, and if not found in the environment of the formula.
Pronouns
When used with data, f_eval provides two pronouns to make it
possible to be explicit about where you want values to come from:
.env and .data. These are thin wrappers around .data
and .env that throw errors if you try to access non-existent values.
Examples
f_eval(~ 1 + 2 + 3)
#> [1] 6
# formulas automatically capture their enclosing environment
foo <- function(x) {
y <- 10
~ x + y
}
f <- foo(1)
f
#> ~x + y
#> <environment: 0x60f6c7e8bfc0>
f_eval(f)
#> [1] 11
# If you supply data, f_eval will look their first:
f_eval(~ cyl, mtcars)
#> [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
# To avoid ambiguity, you can use .env and .data pronouns to be
# explicit:
cyl <- 10
f_eval(~ .data$cyl, mtcars)
#> [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
f_eval(~ .env$cyl, mtcars)
#> [1] 10
# Imagine you are computing the mean of a variable:
f_eval(~ mean(cyl), mtcars)
#> [1] 6.1875
# How can you change the variable that's being computed?
# The easiest way is "unquote" with uq()
# See ?f_interp for more details
var <- ~ cyl
f_eval(~ mean( uq(var) ), mtcars)
#> [1] 6.1875