new_function2: Create new function that supports 'quasi-quosure' syntax

View source: R/language.R

new_function2R Documentation

Create new function that supports 'quasi-quosure' syntax

Description

Create new function that supports 'quasi-quosure' syntax

Usage

new_function2(
  args = alist(),
  body = {
 },
  env = parent.frame(),
  quote_type = c("unquoted", "quote", "quo"),
  quasi_env = parent.frame()
)

Arguments

args

named list of function formals

body

function body expression, supports 'quasi-quosure' syntax

env

declare environment of the function

quote_type

character, whether body is unquoted, quoted, or a 'quo' object (from 'rlang' package)

quasi_env

where the 'quasi-quosure' should be evaluated, default is parent environment

Details

An unquoted body expression will be quoted, all the expressions with 'quasi-quosure' like !!var will be evaluated and substituted with the value of var. For a 'quosure', quo_squash will be applied. A quoted expression will not be substitute, but will be expanded if any 'quasi-quosure' detected

args must be a list object, see formals. For arguments with no default values, or quoted defaults, use alist. An arg=alist(a=) will result in a function like function(a){...}. See examples for more details.

Value

a function

See Also

new_function

Examples


# ------------ standard usage ------------
x <- 1:10
f1 <- new_function2(alist(a=), { print(a + x) }, env = environment())
f1(0)

x <- 20:23
f1(0)  # result changed as x changed

# ------------ 'quasi-quosure' syntax ------------
x <- 1:10
f2 <- new_function2(alist(a=), { print(a + !!x) })
print(f2)

f2(0)

x <- 20:23
f2(0)  # result doesn't change as f2 doesn't depend on x anymore

# ------------ argument settings ------------

default <- 123

# default with values pre-specified
new_function2(list(a = default))   # function (a = 123){}

# default with values unevaluated
new_function2(list(a = quote(default)))   # function (a = default){}
new_function2(alist(a = default))

# missing default
new_function2(alist(a = ))    # function (a){}



dipsaus documentation built on June 27, 2024, 5:10 p.m.