Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple bind_rows with R Dplyr

Tags:

r

dplyr

bind

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]))
}
like image 269
Pablo Quiroz Avatar asked Feb 07 '26 19:02

Pablo Quiroz


2 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]))
}
like image 82
akrun Avatar answered Feb 09 '26 10:02

akrun


We could use sapply

result <- sapply(files, read_excel, simplify=FALSE) %>% 
    bind_rows(.id = "id")
like image 35
TarJae Avatar answered Feb 09 '26 11:02

TarJae



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!