Tea Tree
Tea Tree

Reputation: 984

Pass string as argument to paste function

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.

Upvotes: 2

Views: 688

Answers (2)

Artem Sokolov
Artem Sokolov

Reputation: 13731

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"

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

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"

Upvotes: 1

Related Questions