R: Invoke a function with a list of arguments

invoke {rlang} | R Documentation

## Invoke a function with a list of arguments

### Description

Normally, you invoke a R function by typing arguments manually. A powerful alternative is to call a function with a list of arguments assembled programmatically. This is the purpose of `invoke()`.

### Usage

    invoke(.fn, .args = list(), ..., .env = caller_env(),
      .bury = c(".fn", ""))

### Arguments

`.fn` | A function to invoke. Can be a function object or the name of a function in scope of `.env`.
`.args, ...` | List of arguments (possibly named) to be passed to `.fn`.
`.env` | The environment in which to call `.fn`.
`.bury` | A character vector of length 2. The first string specifies which name should the function have in the call recorded in the evaluation stack. The second string specifies a prefix for the argument names. Set `.bury` to `NULL` if you prefer to inline the function and its arguments in the call.

### Details

Technically, `invoke()` is basically a version of `base::do.call()` that creates cleaner call traces because it does not inline the function and the arguments in the call (see examples). To achieve this, `invoke()` creates a child environment of `.env` with `.fn` and all arguments bound to new symbols (see `env_bury()`). It then uses the same strategy as `eval_bare()` to evaluate with minimal noise.

### Life cycle

`invoke()` is soft-deprecated in favour of `exec()`. Now that we understand better the interaction between unquoting and dots capture, we can take a simpler approach in `exec()`.

If you need finer control over the generated call, you should construct an environment and call yourself, manually burying large objects or complex expressions.

### Examples

    # invoke() has the same purpose as do.call():
    invoke(paste, letters)

    # But it creates much cleaner calls:
    invoke(call_inspect, mtcars)

    # and stacktraces:
    fn <- function(...) sys.calls()
    invoke(fn, list(mtcars))

    # Compare to do.call():
    do.call(call_inspect, mtcars)
    do.call(fn, list(mtcars))

    # Specify the function name either by supplying a string
    # identifying the function (it should be visible in .env):
    invoke("call_inspect", letters)

    # Or by changing the .bury argument, with which you can also change
    # the argument prefix:
    invoke(call_inspect, mtcars, .bury = c("inspect!", "col"))

[Package rlang version 0.4.1 Index]