From this post I got a script that exports a list as separate worksheets in an Excel file (code as below). Now I would like to wrap it in a convenient function to reproduce this behavior by providing the input list name and output file name.
Sample data:
var1 <- list('2003' = 1:3, '2004' = c(4:3), '2005' = c(6,4,1), '2006' = 1:4 )
Current script:
require("XLConnect")
wb <- loadWorkbook("var1.xlsx", create = TRUE)
createSheet(wb, names(var1))
writeWorksheet(wb, var1, names(var1),header=FALSE)
saveWorkbook(wb)
Disclaimer: While I blush to ask such a simple question, I’m sure many other visitors to SO will love to find this information here ;7)
EDIT :: ready-to-use function:
save.excel <-function(.list, default = 'var1', path = ''){
require("XLConnect")
.name <- as.list(match.call())[2]
if(is.language(.name[[1]])) wb_name <- paste0(paste0(path, default, collapse = '/'), '.xlsx')
if(is.symbol(.name[[1]])) wb_name <- paste0(paste0(path, as.character(.name), collapse = '/'), '.xlsx')
wb <- loadWorkbook(wb_name, create = TRUE)
createSheet(wb, names(.list))
writeWorksheet(wb,.list, names(.list),header=FALSE)
saveWorkbook(wb)
}
The only difference from the solution below is that I added XLConnect as a library requested from inside the function, in case you didn’t do it manually before ;7)
This is untested, as XLConnect will not install on my machine. but something like the following might work
Simple approach
A function with two arguments
my_list– the list which you wish to export elements of as separate worksheetswb_name– the name of the workbookThe function looks like this
fancy option that will use the name of the list
If you want to use the name of the
listto create the file then you can have fun withmatch.call,is.symbolandis.language. Details of why you do this are belowthe
is.language/is.symbol/match.calldeal with the two situationsand