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

Description Usage Arguments Details Value See Also Examples

View source: R/language.R

Description

Create new function that supports 'quasi-quosure' syntax

Usage

1
2
3
4
5
6
7
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# ------------ 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 Sept. 6, 2021, 5:08 p.m.