Taz
Taz

Reputation: 5983

R get argument names from function call

I'd like to get argument names from function call:

testFun <- function(x = 1:20, z = list(a = 1, b = 2)) x %>% sin %>% sum

getArgNames <- function(value) {
  # function should return all arguments names - in this case c("x", "z")

}
arg.names <- getArgNames(testFun())

And it is important to not to evaluate function before getting argument names. Any ideas?

Upvotes: 4

Views: 2234

Answers (2)

Aur&#232;le
Aur&#232;le

Reputation: 12819

Using the same formalArgs suggested by @Akrun (and also in the almost duplicate Get the argument names of an R function):

getArgNames <- function(value) formalArgs(deparse(substitute(value)[[1]]))

substitute(value) quotes the input, to prevent immediate evaluation, [[1]] retrieves the function from the parsed input, deparse turns it into character (since formalArgs can take the function name as character).

getArgNames(testFun())

#[1] "x" "z"

Upvotes: 4

akrun
akrun

Reputation: 887078

We can use formalArgs

formalArgs(testFun)
#[1] "x" "z"

If we need to pass the parameter as executable function

library(rlang)
getArgNames <- function(value) {
     v1 <- enquo(value)
     args <- formalArgs(get(gsub("[()]", "", quo_name(v1))))
     list(args, value)
     }

getArgNames(testFun())
#[[1]]
#[1] "x" "z"

#[[2]]
#[1] 0.9982219

Upvotes: 2

Related Questions