Whenever I try to add worksheets and add datasets into workbook I get an error:
Error: This Workbook only has 1 sheets, 4 is not valid
. Is there a way to multiple worksheets and write data into the workbook? I would like to use openxlsx
because of the formating features.
library(openxlsx)
mtcars_list <- split(mtcars, mtcars$cyl)
wb <- createWorkbook()
for (i in mtcars_list){
addWorksheet(wb, unique(i$cyl))
writeData(wb, unique(i$cyl), i)
}
CodePudding user response:
From the documentation
sheet: The worksheet to write to. Can be the worksheet index or name.
Since cyl is numeric, it tries to map it to the fourth sheet, which is not present. Just wrap it into as.character()
library(openxlsx)
mtcars_list <- split(mtcars, mtcars$cyl)
wb <- createWorkbook()
for (i in mtcars_list){
addWorksheet(wb, sheetName = unique(i$cyl))
# as.character
writeData(wb, sheet = as.character(unique(i$cyl)), i)
}
CodePudding user response:
The problem is created by your writeData()
line.
A quick 'dirty' fix would be to just let it run sheet by sheet:
library(openxlsx)
mtcars_list <- split(mtcars, mtcars$cyl)
wb <- createWorkbook()
SHEET <- 1
for (i in mtcars_list){
addWorksheet(wb, unique(i$cyl))
writeData(wb, SHEET, i)
SHEET <- SHEET 1
}
rm(SHEET)
This will tell your loop to jump to the next sheet for every new i. I called it 'dirty' because this will get error prone with larger i's, and since the SHEET
will get saved in your global environment you should delete it after the loop, to make sure it does not mess up the next time you run the code.