SCW16
SCW16

Reputation: 423

cbind dataframe in R with placeholders

Imagine I have three dataframes:

data.frame1 <- data.frame(x=c(1:10))
data.frame2 <- data.frame(x=c(11:20))
data.frame3 <- data.frame(x=c(21:30))

I could bind them together by explicitely naming each of them:

res.data.frame <- cbind(data.frame1, data.frame2, data.frame3)

However, I am looking for more dynamic ways to do so, e.g. with placeholders.

This saves somehow the three dataframes in a new dataframe, but not in a usable format:

res.data.frame1 <- as.data.frame(mapply(get, grep("^data.frame.$", ls(), value=T)))

enter image description here

This command would only save the three names:

res.data.frame2 <- grep(pattern = "^data.frame.$", ls(), value=T)

This one only gives an error message:

res.data.frame3  <- do.call(cbind, lapply(ls(pattern = "^data.frame.$")), get)

Does anyone know the right way to do this?

Upvotes: 0

Views: 194

Answers (1)

CPak
CPak

Reputation: 13591

Something like this maybe?

Assuming ls()

# [1] "data.frame1" "data.frame2" "data.frame3"

as.data.frame(Reduce("cbind", sapply(ls(), function(i) get(i))))

Based on @akrun's comment, this can be simplified to

as.data.frame(Reduce("cbind", mget(ls())))

Upvotes: 3

Related Questions