Use R and Openxlsx to output a list of dataframes as worksheets in a single Excel file
I don't have your data frames, so I can't test this, but the code below is similar to the approach I use when I need to read and write Excel files. The code below uses the xlsx
package, as that's what I'm familiar with, but hopefully you can adapt it if you need to use openxlsx
.
library(xlsx)
First, read the files into a list. Something like this:
filePath <- "../02benchmark/results/results_20170330/"
filePattern <- "*.csv"
fileListwithPath = list.files(path = filePath,
pattern = filePattern,
full.names = TRUE)
fileList = list.files(path = filePath, pattern = filePattern, full.names = FALSE)
fileListwithPath = setNames( fileListwithPath,
list.files(path = filePath, pattern = filePattern))
df.list = lapply(fileListwithPath, read.csv)
# Now we rename the List Names for use in worksheets...
# Remove .csv and sample_ prefix used in filenames...
# Reult in workbook S<size>_<R version>_<date>
names(df.list) <- gsub("\\.csv$","", names(df.list))
names(df.list) <- gsub("sample_","S", names(df.list))
You now have a list in which each element is a data frame and each element's name is the name of the file. Now, let's write each data frame to a different worksheet in the same Excel workbook and then save the file as an xlsx file:
wb = createWorkbook()
lapply( names(df.list),
function(df) {
sheet = createSheet(wb, df)
addDataFrame(df.list[[df]], sheet = sheet, row.names = FALSE)
} )
saveWorkbook(wb, "My_workbook.xlsx")
I've separated reading and writing the csv files for illustration, but you can combine them into a single function that reads each individual csv file and writes it to a new sheet in a single Excel workbook.
Here's the solution with openxlsx
:
## create data;
dataframes <- split(iris, iris$Species)
# create workbook
wb <- createWorkbook()
#Iterate the same way as PavoDive, slightly different (creating an anonymous function inside Map())
Map(function(data, nameofsheet){
addWorksheet(wb, nameofsheet)
writeData(wb, nameofsheet, data)
}, dataframes, names(dataframes))
## Save workbook to excel file
saveWorkbook(wb, file = "file.xlsx", overwrite = TRUE)
.. however, openxlsx
is also able to use it's function openxlsx::write.xlsx
for this, so you can just give the object with your list of dataframes and the filepath, and openxlsx
is smart enough to create the list as sheets within the xlsx-file. The code I post here with Map()
is if you want to format the sheets in a specific way.