I'm using the glue
function to merge 2 character vectors together, but glue
returns multiple results. I want the glue
function to return one result, but I don't know how. The replicable code is as follows:
library(glue)
a = c('cyl', 'mpg')
b = 'carb'
# glue result
glue("mtcars[{c(a, b)}]")
# mtcars[cyl]
# mtcars[mpg]
# mtcars[carb]
# the result I expected
mtcars[c('cyl', 'mpg', 'carb')]
As mentioned by @MrFlick you can do this with help of glue
and glue_collapse
:
library(glue)
glue("mtcars[c(", glue_collapse(glue("{c(a, b)}"), sep = ","), ")]")
#mtcars[c(cyl,mpg,carb)]
However, it seems easier using base R :
sprintf('mtcars[c(%s)]', toString(c(a, b)))
#[1] "mtcars[c(cyl, mpg, carb)]"