3

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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
John-Henry
  • 1,556
  • 8
  • 20

1 Answers1

5

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"
akrun
  • 874,273
  • 37
  • 540
  • 662
  • thanks! taking this a step further do you have advice on ending the string with `.csv`? -- `hello_x_world.csv` – John-Henry Mar 11 '20 at 21:25
  • 2
    I recommend using `as_string()` instead of `quo_name()` which is likely to be deprecated. If you really want the quo-name behaviour, use the more explicit `as_label()`. But `as_string()` looks right here. See `?as_label`. – Lionel Henry Mar 12 '20 at 08:41