set_default() takes a function and returns a new version with updated default values for specified arguments.

set_default(fun, nms, vls = NULL)

Arguments

fun

A function whose arguments will get new default values.

nms

Character vector of argument names, or something coercible to that (e.g. a call to v()).

vls

Optional vector or list of values to use as defaults. If nms is a named list, vls can be NULL.

Value

A new function with updated default values in its formals.

Details

This is useful when you want to programmatically create specialized versions of a function with certain arguments preset to default values.

  • The specified arguments will be moved to the end of the formal argument list in the returned function.

  • You can supply arguments as a named list or as separate names and values.

Examples

## Simple example
f1 <- function(x, y, z) { x + y + z }

## Add defaults for x and y
set_default(f1, list(x = 1, y = 2))
#> function (z, x = 1, y = 2) 
#> {
#>     x + y + z
#> }
#> <environment: 0x5e0103f85940>
# function (z, x = 1, y = 2) { x + y + z }

## Same using separate vectors of names and values
set_default(f1, c("x", "y"), c(1, 2))
#> function (z, x = 1, y = 2) 
#> {
#>     x + y + z
#> }
#> <environment: 0x5e0103f85940>

## Works with v() style if supported
# set_default(f1, v(x, y), c(1, 2))

## Another example with more arguments
f2 <- function(a, b, c, d) { a + b + c + d }
set_default(f2, list(b = 10, d = 5))
#> function (a, c, b = 10, d = 5) 
#> {
#>     a + b + c + d
#> }
#> <environment: 0x5e0103f85940>