Search code examples
rdataframewhile-looprbind

How to rbind multiple dataframes with a while-loop?


I'm trying to rbind multiple loaded datasets (all of them have the same num. of columns, named "num", "source" and "target"). In case, I have ten dataframes, which names are "test1", "test2", "test3" and so on...

I thought that trying the solution below (creating an empty dataframe and looping through the others) would solve my problem, but I guess that I'm missing something in the second argument of the rbind function. I don't know if the solution using paste0("test", I) to increment the variable (changing the name of the dataframe) it's correct... I'm afraid that I'm just trying to rbind a dataframe with a string object (and getting an error), is that right?

test = as.data.frame(matrix(ncol = 3, nrow = 0)) %>%
  setNames(c("num", "source", "target"))
i=1
while (i < 11) {
  test = rbind(test, paste0("test", i))
  i = i + 1
}

Solution

  • We need replicate to return as a list

    out <- setNames(replicate(10, test, simplify = FALSE), 
           paste0("test", seq_len(10)))
    

    If there are multiple datasets already created in the global env, get those in to a list and rbind within do.call

    out <- do.call(rbind, mget(paste0("test", 1:10)))