2

I'm trying to pass string variable names to the paste function to paste all strings together. Here's a mwe:

#bind strings to variable names
a <- c("abc", "def", "ghi")
b <- c("jkl", "mno", "pqr")
c <- c("stu", "vwx", "yz1")

paste(eval(letters[1:3]))
# "a" "b" "c"

What I want is, however, the content of the 3 variables pasted into one string

"abc def ghi jkl mno pqr stu vwx yz1"

I know about quasiquotation and so I've tried

get(letters[1:3])

But this only gives me

"abc def ghi"

I know this topic is covered in insane detail across the internet but I have tried every rlang verb without success.

Tea Tree
  • 882
  • 11
  • 26
  • 1
    If you need to get multiple values, use `mget()` rather than `get()`, the latter only returns the first. They will be returned in a list. So maybe `paste(unlist(mget(letters[1:3])), collapse = " ")` is what you need. None of that is `rlang` though. Using R lang it might look something like this: `rlang::eval_tidy(rlang::expr(paste(c(!!!rlang::syms(letters[1:3])), collapse=" ")))` – MrFlick Aug 31 '20 at 06:04
  • Oh that's simple and actually solves my problem. Thanks! Is there a solution that returns a character vector directly (to avoid unlist)? – Tea Tree Aug 31 '20 at 06:09
  • 1
    There's nothing in base R that will expand to multiple arguments unless you do the `do.call()` route. But here you need to combine all your values some way. I'm not sure what you had in mind as far as how you would have written it `paste(a,b,c)` doesn't return the value you want. you need `paste(c(a,b,c), collapse=" ")` which could be done with `paste(do.call("c", c(mget(letters[1:3]))), collapse=" ")`. But you need something to combine those vectors whether it's a `c()` or `unlist()`. – MrFlick Aug 31 '20 at 06:14
  • The ```paste(unlist(mget``` solution is the most elegant. If you post it, I'll accept it. – Tea Tree Aug 31 '20 at 16:45

2 Answers2

1

The answer suggested by @MrFlick is easy and straightforward. Here is a way using get on individual characters.

paste0(sapply(letters[1:3], get, envir = .GlobalEnv), collapse = " ")
#[1] "abc def ghi jkl mno pqr stu vwx yz1"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

For completeness, to apply quasiquotation you simply need to convert strings to symbols:

s <- lapply( letters[1:3], as.name )
paste( do.call("c", s), collapse=" " )
# [1] "abc def ghi jkl mno pqr stu vwx yz1"
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74