Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

deparse and substitute on ellipsis to get names of parameters

How do I get the names of paramaters used for ellipsis in a function call, independent whether they are packed into a list or not?

The following function works pretty fine if the parameters are passed directly into the function.

foo <- function(...) {
  sapply(substitute(...()), deparse)
}

a <- 1:3
b <- 2:6
foo(a, b)

result: "a" "b"

Now I pack the parameters explicitly into a list, to make my code more pipe-friendly:

foo(list(a, b))

result: "list(a, b)"

The function foo should also work with that, to return only the names a and b. How to handle this within function foo?

Many thanks in advance.

like image 203
stschn Avatar asked Dec 17 '25 05:12

stschn


1 Answers

As a workaround try this

foo <- function(...) {
    x <- substitute(...())
    if(class(x[[1]]) == "call")  sapply(x[[1]][-1] , deparse)
    else sapply(x , deparse)
}

  • Output
> foo(list(a, b))
[1] "a" "b"

> foo(a, b)
[1] "a" "b"

like image 101
Mohamed Desouky Avatar answered Dec 19 '25 21:12

Mohamed Desouky



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!