| as_function {rlang} | R Documentation |
as_function() transforms a one-sided formula into a function.
This powers the lambda syntax in packages like purrr.
as_closure() first passes its argument to as_function(). If
the result is a primitive function, it regularises it to a proper
closure (see is_function() about primitive functions). Some
special control flow primitives like if, for, or break
can't be coerced to a closure.
as_function(x, env = caller_env()) is_lambda(x) as_closure(x, env = caller_env())
x |
A function or formula. If a function, it is used as is. If a formula, e.g. Lambdas currently do not support nse-force, due to the way the arguments are handled internally. |
env |
Environment in which to fetch the function in case |
f <- as_function(~ .x + 1)
f(10)
g <- as_function(~ -1 * .)
g(4)
h <- as_function(~ .x - .y)
h(6, 3)
# Functions created from a formula have a special class:
is_lambda(f)
is_lambda(as_function(function() "foo"))
# Primitive functions are regularised as closures
as_closure(list)
as_closure("list")
# Operators have `.x` and `.y` as arguments, just like lambda
# functions created with the formula syntax:
as_closure(`+`)
as_closure(`~`)
# Use a regular function for tidy evaluation, also when calling functions
# that use tidy evaluation:
## Bad:
e <- as_function(~ as_label(ensym(.x)))
## Good:
e <- as_function(function(x) as_label(ensym(x)))
e(y)