Search code examples
rwildcardplaceholdercbind

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?


Solution

  • 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())))