Search code examples
rrlangnon-standard-evaluation

Pass vector of symbols as function argument and convert to character vector


I have a function that I want to pass as an argument a vector of symbols and then internally I want to convert that vector to a character vector.

Minimal example:

fun <- function(symbols = c(a, b, c)) {
 # code to convert to character vector 
}

fun()

Output:

[1] "a" "b" "c"

Solution

  • Here's an approach with rlang::quo_name:

    library(rlang)
    fun <- function(symbols = c(a, b, c)) {
      symbols <- enquo(symbols)
      string <- quo_name(symbols)
      unlist(strsplit(gsub("(c\\(|\\)|\\s)","",string),","))
    }
    
    fun(c(apple, orange, pear))
    #[1] "apple"  "orange" "pear"
    

    I suspect you're actually trying to solve another problem with this, so it probably makes sense to post that as another question.