Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of data.frame's to individual excel worksheets - R

Tags:

r

excel

xlsx

I have a list of data.frame's that I would like to output to their own worksheets in excel. I can easily save a single data frame to it's own excel file but I'm not sure how to save multiple data frames to the their own worksheet within the same excel file.

library(xlsx)
write.xlsx(sortedTable[1], "c:/mydata.xlsx")
like image 574
Barnaby Hussey-Yeo Avatar asked Dec 17 '14 11:12

Barnaby Hussey-Yeo


2 Answers

The following code works perfectly, which is from:https://rpubs.com/gbganalyst/RdatatoExcelworkbook

packages <- c("openxlsx", "readxl", "magrittr", "purrr", "ggplot2")

if (!require(install.load)) {
  install.packages("install.load")
}
install.load::install_load(packages)

list_of_mydata

write.xlsx(list_of_mydata, "Excel workbook.xlsx")
like image 106
Yale Liu Avatar answered Sep 18 '22 18:09

Yale Liu


lets say your list of data frames is called Lst and that the workbook you want to save to is called wb.xlsx. Then you can use:

library(xlsx)
counter <- 1
for (i in length(Lst)){
   write.xlsx(x=Lst[[i]],file="wb.xlsx",sheetName=paste("sheet",counter,sep=""),append=T)
   counter <- counter + 1
}

G

like image 35
PavoDive Avatar answered Sep 21 '22 18:09

PavoDive