Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create function arguments from a character vector

Tags:

r

rlang

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.

like image 721
jandraor Avatar asked Jul 23 '26 12:07

jandraor


1 Answers

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=)))
like image 199
G. Grothendieck Avatar answered Jul 26 '26 07:07

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!