Search code examples
rrlang

Create function arguments from a character vector


Using the rlang package, I can create a function with the following expression:

new_function(pairlist2(a = , b = ), quote(a * b))

Imagine that I have a & b in a character vector:

arg_names <- c("a", "b")

How could I use arg_names to create the function arguments?

It's important to mention that I don't know the number of parameters beforehand. Another procedure returns the parameters, which can vary.


Solution

  • There is already a good answer but since the question did use the rlang tag we can use the rlang missing_arg function. We will extract the variables from the body to get the arguments and assume they are in the order encountered but we could supply args <- c("a", "b") if that were preferable.

    library(purrr)
    library(rlang)
    
    # input
    f <- function() a * b
    
    args <- all.vars(body(f)) # or use args <- c("a","b")
    formals(f) <- map(set_names(args), ~ missing_arg())
    
    f
    ## function (a, b) 
    ## a * b
    

    The corresponding base R code would be:

    formals(f) <- sapply(args, \(x) unname(alist(x=)))