Alexander Vornsand
Alexander Vornsand

Reputation: 39

How to paste together all the objects in an environment in R?

This seems like a simple question, but I can't find a solution. I want to take all of the objects (character vectors) in my environment and use them as arguments in a paste function. But the catch is I want to do so without specifying them all individually.

a <- "foo"
b <- "bar"
c <- "baz"

z <- paste(a, b, c, sep = " ")
z
[1] "foo bar baz"

I imagine that there must be something like the ls() would offer this, but obviously

z <- paste(ls(), collapse = " ")
z
[1] "a b c"

not "foo bar baz", which is what I want.

Upvotes: 1

Views: 218

Answers (1)

akrun
akrun

Reputation: 887611

We can use mget to return the values of the objects in a list and then with do.call paste them into a single string

do.call(paste, c(mget(ls()), sep= " "))

As the sep is " ", we don't need that in paste as it by default giving a space

do.call(paste, mget(ls()))

Upvotes: 2

Related Questions