'Glue vector to string

I want to produce this string: All my variables: a, b, c from this variable vars <- c("a", "b", "c") using glue().

My best attempt so far is:

library(glue)
glue('All my variables: {paste(vars, collapse = ", ")}')

Question:

Is there any easier / cleaner way of to implement it that i oversee?

Other attempts:

The following obviously fail, i just want to show that i looked into the docu and made some effort :).

glue('All my variables: {vars}')
glue_data('All my variables: {vars}', .sep = ", ")


Solution 1:[1]

You can just do,

paste('All my variables:', toString(vars))
#[1] "All my variables: a, b, c"

Solution 2:[2]

you can also use glue::glue_collapse() :

vars <- c("a", "b", "c")
glue("All my variables : {glue_collapse(vars,  sep = ', ')}")
#> All my variables : a, b, c

Solution 3:[3]

This can be done easily without any packages at all. Here are some possibilities:

# 1
paste("All my variables:", toString(vars))
## [1] "All my variables: a, b, c"

# 2
sprintf("All my variables: %s", toString(vars))
## [1] "All my variables: a, b, c"

# 3
sub("@", toString(vars), "All my variables: @")
## [1] "All my variables: a, b, c"

If you are looking to do this to output a warning or error message:

# 4a
warning("All my variables: ", toString(vars))
## Warning message:
## All my variables: a, b, c 

# 4b
stop("All my variables: ", toString(vars))
## Error: All my variables: a, b, c

With fn$ from the gsubfn package. Preface any function call with fn$ (such as c here) and then the arguments will be processed using quasi-perl string interpolation.

# 5
library(gsubfn)
fn$c("All my variables: `toString(vars)`")
## [1] "All my variables: a, b, c"

or

# 6
library(gsubfn)
string <- toString(vars)
fn$c("All my variables: $string")
## [1] "All my variables: a, b, c"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sotos
Solution 2 moodymudskipper
Solution 3