0

I have to generate multiple data frames in a loop. How to generate a single output excel/CSV file comprising all the data frames in R?

  • Should the resulting Excel workbook contain one worksheet per data frame, or should all data frames be combined into a single worksheet? Does each data frame contain the same columns? – Len Greski Jul 06 '20 at 19:22

2 Answers2

0

You can just put all of your dataframes in a list and use the openxlsx package:

library(openxlsx)

openxlsx::write.xlsx(list_of_dataframes, "File Name.xlsx", row.names = FALSE)

This will write out one Excel file, with a tab for each list object.

Example with iris and mtcars:

data(mtcars)
data(iris)

list_of_dataframes <- list(mtcars, iris)

openxlsx::write.xlsx(list_of_dataframes, "File Name.xlsx", row.names = FALSE)
Matt
  • 7,255
  • 2
  • 12
  • 34
0

If you want to stick with the loop, you can do the following:

final <- data.frame()

for (i in 1:n){
   
  # computations to generate data frame
  df <- ... 

  # bind the data frame to the final result
  final <- rbind(final, df)
}

This will combine all the data frames you generate within your loop into one large one, called final. Now to save final as a .csv:

readr::write_csv(final, path = "output.csv")
Count Orlok
  • 997
  • 4
  • 13