bschneidr
bschneidr

Reputation: 6278

With rlang, convert contents of `...` to a character vector

I'd like to be able to create a character vector based on the names supplied to the ... part of a function.

For instance, if I have the function foo(...) and I type foo(x, y), how do I create a character vector that looks like c("x", "y")?

I'm most interested in figuring out how to use rlang for this, but base solutions would be great as well.

Upvotes: 4

Views: 205

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

Do you mean something like this?

foo <- function(...) unname(purrr::map_chr(rlang::exprs(...), as.character))
foo(x, y)
#[1] "x" "y"

identical(foo(x, y), c("x", "y"))
#[1] TRUE

Alternatively we can use as.character directly on the list returned from rlang::exprs

foo <- function(...) as.character(rlang::exprs(...))

In response to @joran's question, I'm not sure to be honest; consider the following case

as.character(rlang::exprs(NULL, a, b))
#[1] "NULL" "a" "b"

map_chr(rlang::exprs(NULL, a, b), as.character)
#Error: Result 1 is not a length 1 atomic vector

So as.character converts NULL to "NULL" whereas map_chr(..., as.character) throws an error on account of the NULL list entry.

Upvotes: 4

Related Questions