1

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 = ", ")
Zoe
  • 27,060
  • 21
  • 118
  • 148
Tlatwork
  • 1,445
  • 12
  • 35

3 Answers3

6

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
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
4

You can just do,

paste('All my variables:', toString(vars))
#[1] "All my variables: a, b, c"
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • 1
    thank you for the answer. As specified i would like to stay with glue (for consistency). But `toString()` is great and can be combined with glue as i saw. Thanks a lot! – Tlatwork Sep 04 '19 at 13:51
2

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"
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • thank you for the answer. As specified i would like to stay with glue (for consistency). But `toString()` is great and can be combined with glue as i saw. Thanks a lot! I accepted Sotos answer as he was a bit faster, i hope thats fine for you. – Tlatwork Sep 04 '19 at 13:51
  • 1
    Actually the question asked was "Is there any easier / cleaner way of to implement it that i oversee?" and eliminating dependencies with no additional complication seems cleaner. – G. Grothendieck Sep 04 '19 at 14:38
  • fair Point. I wasnt specific enough there, sry. – Tlatwork Sep 04 '19 at 14:48