Search code examples
rdplyrbind

Multiple bind_rows with R Dplyr


I need to bind_row 27 excel files. Although I can do it manually, I want to do it with a loop. The problem with the loop is that it will bind the first file to i and then the first file to i+1, hence losing i. How can I fix this?

nm <- list.files(path="sample/sample/sample/")

df <- data.frame()

for(i in 1:27){
  my_data <- bind_rows(df, read_excel(path = nm[i]))
}

Solution

  • We could loop over the files with map, read the data with read_excel and rbind with _dfr

    library(purrr)
    my_data <- map_dfr(nm, read_excel)
    

    In the Op's code, the issue is that in each iteration, it is creating a temporary dataset 'my_data', instead, it should be binded to the original 'df' already created

    for(i in 1:27){
      df <- rbind(df, read_excel(path = nm[i]))
    }