Multiple bind_rows with R Dplyr

Viewed 103

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

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

We could use sapply

result <- sapply(files, read_excel, simplify=FALSE) %>% 
    bind_rows(.id = "id")

You can still use your for loop:

my_data<-vector('list', 27)
for(i in 1:27){
  my_data[i] <- read_excel(path = nm[i])
}
do.call(rbind, my_data)
Related