How to rbind multiple dataframes with a while-loop?

Viewed 238

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
}
3 Answers

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

We could bind test1:test10 using the common pattern in the name:

library(dplyr)
result <- mget(ls(pattern="^test\\d+")) %>%
    bind_rows()

If I understood correctly, this might help you

Libraries

library(dplyr)

Example data

list_of_df <-
  list(
  df1 = data.frame(a = "1"),
  df2 = data.frame(a = "2"),
  df3 = data.frame(a = "1"),
  df4 = data.frame(a = "2")
)

Code

bind_rows(list_of_df,.id = "dataset")

Result

  dataset a
1     df1 1
2     df2 2
3     df3 1
4     df4 2
Related