Kalsi
Kalsi

Reputation: 21

Call multiple variables using for loop

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
}

Upvotes: 0

Views: 232

Answers (2)

Santosh M.
Santosh M.

Reputation: 2454

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".

Upvotes: 3

pogibas
pogibas

Reputation: 28379

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)
}

Upvotes: 1

Related Questions