4

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?

Taz
  • 5,755
  • 6
  • 26
  • 63
  • It is not duplicate, because I want to extract argument names from evaluated function call, not from function name only. – Taz May 28 '18 at 10:08

2 Answers2

4

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"
Aurèle
  • 12,545
  • 1
  • 31
  • 49
2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Good idea, but `formalArgs` works on function name `formalArgs(testFun)`, not on evaluated function: `formalArgs(testFun())`. – Taz May 28 '18 at 08:18
  • 2
    @Taz Then maybe `getArgNames <- function(value) formalArgs(deparse(substitute(value)[[1]]))` – Aurèle May 28 '18 at 08:28
  • @akrun Do you mind if I turn my comment into a separate answer, since the syntax I use differs enough from yours? – Aurèle May 28 '18 at 09:37
  • @Aurèle Sure you can do that – akrun May 28 '18 at 09:38