Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

new_function

Create a function


Description

Stable lifecycle

This constructs a new function given its three components: list of arguments, body code and parent environment.

Usage

new_function(args, body, env = caller_env())

Arguments

args

A named list or pairlist of default arguments. Note that if you want arguments that don't have defaults, you'll need to use the special function pairlist2(). If you need quoted defaults, use exprs().

body

A language object representing the code inside the function. Usually this will be most easily generated with base::quote()

env

The parent environment of the function, defaults to the calling environment of new_function()

Examples

f <- function() letters
g <- new_function(NULL, quote(letters))
identical(f, g)

# Pass a list or pairlist of named arguments to create a function
# with parameters. The name becomes the parameter name and the
# argument the default value for this parameter:
new_function(list(x = 10), quote(x))
new_function(pairlist2(x = 10), quote(x))

# Use `exprs()` to create quoted defaults. Compare:
new_function(pairlist2(x = 5 + 5), quote(x))
new_function(exprs(x = 5 + 5), quote(x))

# Pass empty arguments to omit defaults. `list()` doesn't allow
# empty arguments but `pairlist2()` does:
new_function(pairlist2(x = , y = 5 + 5), quote(x + y))
new_function(exprs(x = , y = 5 + 5), quote(x + y))

rlang

Functions for Base Types and Core R and 'Tidyverse' Features

v0.4.11
MIT + file LICENSE
Authors
Lionel Henry [aut, cre], Hadley Wickham [aut], mikefc [cph] (Hash implementation based on Mike's xxhashlite), Yann Collet [cph] (Author of the embedded xxHash library), RStudio [cph]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.