I'm looking for a way to automate some data clean-up. So far, I've figured out how to import several excel workbooks and all their sheets into R using the following:
my_data = expand_grid(
file = list.files("~path", full.names = TRUE),
sheet = seq(6)
) %>%
transmute(data = file %>% map2(sheet, ~ read_excel(path = .x, sheet = .y, skip = 2))) %>%
pull(data)
What I need help with is exporting all of the resulting tibbles into an Excel workbook, one tibble per sheet.
I'm using the following method to try to print (based on a previously answered question):
library(openxlsx)
library(tibble)
output_expediter <- function(df, output_filename) {
nm1 <- deparse(substitute(df))
wb <- createWorkbook()
addWorksheet(wb, sheetName = nm1)
writeData(wb, sheet= nm1, x = df)
saveWorkbook(wb =wb, file = output_filename, overwrite = TRUE)
}
I get the following error:
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 4, 52, 8, 0, 5
It is true that all the tibbles differ in row numbers.I'm unsure of how to proceed.
Any help would be greatly appreciated.
Here is a way to do it:
How it works
set_nameswhich gives a named vector, where the names and values (for the moment) are the file path to the workbooks.mapand to each element we applyrio::import_list. This will import all sheets of a workbook, preserving the sheet names. By doing this, we have preserved both the workbook path AND the worksheet names:writexl::write_xlsxwill use the list names as sheet names.Data
I created some fake workbooks in my current working directory: