John-Henry
John-Henry

Reputation: 1807

Converting tidyeval arguments to string

I have a simple function in R with ... using tidyeval. Is is possible to change these into a string?

simple_paste <- function(...){
  my_vars <- enquos(...)
  paste(..., sep = "_x_")
}

simple_paste(hello, world)

As an output, I would like to get "hello_x_world". I could also consider using the glue function or str_c instead of paste, although I'm not sure that would be better.

Upvotes: 4

Views: 444

Answers (1)

akrun
akrun

Reputation: 887108

Convert the quosure to character and then paste

simple_paste <- function(...) {
  purrr::map_chr(enquos(...), rlang::as_label) %>% 
          paste(collapse="_x_")
   }
simple_paste(hello, world)
#[1] "hello_x_world"

Or another option is to evaluate an expression

simple_paste <- function(...)  eval(expr(paste(!!! enquos(...), sep="_x_")))[-1]
simple_paste(hello, world)
#[1] "hello_x_world"

if we need .csv at the end

simple_paste <- function(...)  eval(expr(paste0(paste(!!! enquos(...), sep="_x_"), ".csv")))[-1]
simple_paste(hello, world)
#[1] "hello_x_world.csv"

Upvotes: 5

Related Questions