1

In R, I have two strings and one vector containing several strings.

str1 <- "this_guy"
str2 <- "that_guy"
strvec <- c("str3", "str4", "str5")

How can I paste these together so that I get:

"str1 + str2 + str3 + str4 + str5"

A straightforward application of paste() such as

paste(str1, str2, strvec, sep = "+")

doesn't work

Sotos
  • 51,121
  • 6
  • 32
  • 66
ben
  • 787
  • 3
  • 16
  • 32
  • 2
    even better to use `reformulate`. – lmo Sep 01 '17 at 15:59
  • Possible duplicates: https://stackoverflow.com/questions/4951442/formula-with-dynamic-number-of-variables and https://stackoverflow.com/questions/9238038/passing-a-vector-of-variables-into-lm-formula . – lmo Sep 01 '17 at 16:04

1 Answers1

3

I am not sure which one you mean (names or vectors) so here are both. You can use ls to capture the pattern str[0-9]+ from your global environment or mget(ls(...)) to get the actual string., i.e.

paste(c(ls(pattern = 'str[0-9]+'), strvec), collapse = ' + ')
#[1] "str1 + str2 + str3 + str4 + str5"

paste(c(mget(ls(pattern = 'str[0-9]+')), strvec), collapse = ' + ')
#[1] "this_guy + that_guy + str3 + str4 + str5"
Sotos
  • 51,121
  • 6
  • 32
  • 66