user3603486
user3603486

Reputation:

How can I apply quote to every argument in a function

Here's what I'd like to do:

as.character(quote(x))
[1] "x"

Now I would like to put it in a function.

qq <- function(a) as.character(substitute(a))
qq(x)
[1] "x"

Fine. But:

qq <- function(...) as.character(substitute(...))
qq(x,y,z)
[1] "x"

OK, how about:

qq <- function(...) sapply(..., function (x) as.character(substitute(x)))
qq(x,y,z)
Error in get(as.character(FUN), mode = "function", envir = envir) : 
object 'y' of mode 'function' was not found 

And:

qq <- function(...) sapply(list(...), function (x) as.character(substitute(x)))
qq(x,y,z)
Error in lapply(X = X, FUN = FUN, ...) : object 'z' not found 

Is there a way to do this?

Upvotes: 3

Views: 893

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

You could try match.call

foo <- function(...) {
    sapply(as.list(match.call())[-1], deparse)
}
foo(x, y, z)
# [1] "x" "y" "z"
foo(a, b, c, d, e)
# [1] "a" "b" "c" "d" "e"

If there are any other arguments, you may want some variation of the above function.

foo2 <- function(x, ...) {
    a <- as.list(match.call(expand.dots = FALSE))$...
    sapply(a, deparse)
}
foo2(5, x, y, z)
# [1] "x" "y" "z"

Upvotes: 4

G. Grothendieck
G. Grothendieck

Reputation: 269586

Try this:

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

Note: qq <- function(...) as.character(substitute(...)) does work if passed a single argumet: qq(a) so the problem is that substitute is expecting a single argument, not several. The {...} converts the multiple arguments to one.

Upvotes: 3

Related Questions