R: Vectorize deparse(substitute(x))

Viewed 62

I want to vectorize deparse(substitute(x)).

f <- function(...){
deparse(substitute(...))
}

f(a, b, c)

This gives only the first element, "a", but I await "a", "b", "c". By accident, I found this

f2 <- function(...){
deparse(substitute(...()))
}
f2(ab, b, c)

This gives "pairlist(ab, b, c)". Now I could delete all the stuff I do not need to obtain "a", "b", "c". But this seems not elegant to me. Is there a way to vectorize deparse(substitute(x))?

I know there is a question with a similar issue but the answer does not include deparse(substitute(x)).

2 Answers

We can use match.call

f <- function(...) sapply(as.list(match.call())[-1], as.character)
f(a)
#[1] "a"
f(a, b)
#[1] "a" "b"
f(a, b, c)
#[1] "a" "b" "c"

Or using substitute

f <- function(...) sapply(substitute(...()), deparse)
f(a)
#[1] "a"
f(a, b)
#[1] "a" "b"
f(a, b, c)
#[1] "a" "b" "c"

match.call is a good starting point. I'd encourage you to explore all what you can do with it. I believe this gets you where you want though:

f <- function(...){
    as.character(match.call(expand.dots = FALSE)[[2]])
}

and an example of using it...

f(hey, you)
[1] "hey" "you"
Related