0

I want to combine two data frames from variable list using for loop. I am using following code for creating and combining data frame column wise.

tu1<-data.frame(c(1,2,3),c(2,5,6))
tu2<-data.frame(c(5,5,37),c(21,52,61))
Consolidate<-function(){
  tx<-data.frame(0)
  for(i in :2){
    namefile1<-paste("tu",as.character(i),sep = "")
    tr<-namefile1
    tx<-data.frame(cbind(tr,tx))
  }
  tx
}
3
  • What's your expected output? Commented Oct 23, 2017 at 11:37
  • I have 117 data frame from tu1 to tu117. I want to combine them column wise. Commented Oct 23, 2017 at 11:44
  • Do you have similar column names? Commented Oct 23, 2017 at 11:44

2 Answers 2

3

You can just use one liner as below:

do.call(cbind, mget(ls(pattern="^tu\\d+")))

It will combine all data frames with similar patterns in your case "tu".

Sign up to request clarification or add additional context in comments.

Comments

1

Edit:

OP explained that: "I have 117 data frame from tu1 to tu117. I want to combine them column wise". To do so he can:

foo <- grep("tu[1-117]", ls(), value = TRUE)
tuAll <- do.call(cbind, sapply(foo, function(x) get(x)))

Old answer:

I can't imagine why would you want to do this as simple cbind(tu1, tu2) works. If you want to bind multiple times you can use cbind(tu1, tu2, tu1, tu2).

But if you want to bind them using loop (not recommending) this is edited version of your Consolidate() function:

tu1 <- data.frame(c(1,2,3), c(2,5,6))
tu2 <- data.frame(c(5,5,37), c(21,52,61))
Consolidate <- function() {
    for(i in 1:2){
        namefile <- paste0("tu", i)
        if (i == 1) {
            tx <- get(namefile)
        } else {
            tx <- cbind(get(namefile), tx)
        }
    }
    return(tx)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.