Stable lifecycle

  • as_function() transform objects to functions. It fetches functions by name if supplied a string or transforms formulas to function.

  • 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).

as_function(x, env = caller_env())

is_lambda(x)

as_closure(x, env = caller_env())

Arguments

x

A function or formula.

If a function, it is used as is.

If a formula, e.g. ~ .x + 2, it is converted to a function with two arguments, .x or . and .y. This allows you to create very compact anonymous functions with up to two inputs. Functions created from formulas have a special class. Use is_lambda() to test for it.

env

Environment in which to fetch the function in case x is a string.

Examples

f <- as_function(~ . + 1) f(10)
#> [1] 11
# Functions created from a formula have a special class: is_lambda(f)
#> [1] TRUE
is_lambda(as_function(function() "foo"))
#> [1] FALSE
# Primitive functions are regularised as closures as_closure(list)
#> function (...) #> list(...) #> <environment: base>
as_closure("list")
#> function (...) #> list(...) #> <environment: base>
# Operators have `.x` and `.y` as arguments, just like lambda # functions created with the formula syntax: as_closure(`+`)
#> function(.x, .y) if (missing(.y)) .x else .x + .y #> <bytecode: 0x7719238> #> <environment: 0x69f4cc8>
as_closure(`~`)
#> function(.x, .y) { #> if (is_missing(substitute(.y))) { #> new_formula(NULL, substitute(.x), caller_env()) #> } else { #> new_formula(substitute(.x), substitute(.y), caller_env()) #> } #> } #> <bytecode: 0x45c65a0> #> <environment: 0x6fd7f78>