The function of saving the list R in separate Excel sheets

From this post I got a script that exports the list as separate sheets in an Excel file (code as shown below). Now I would like to wrap it in a convenient function to reproduce this behavior by specifying the name of the input list and the name of the output file.

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 am blushing to ask such a simple question, I am sure that many other SO visitors will be happy 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 the library requested inside the function, in case you didn't do it manually before; 7)

+5
2

, XLConnect . -

  • my_list - , .
  • wb_name -

:

write_list <-function(my_list, wb_name = 'var1.xlsx') {    
  wb <- loadWorkbook(wb_name, create = TRUE)
  createSheet(wb, names(my_list))
  writeWorksheet(wb, my_list, names(my_list),header=FALSE)
  saveWorkbook(wb)
 }

fancy,

list , match.call, is.symbol is.language. ,

write_list_name <-function(.list, default = 'var1', path = ''){
  .name <- as.list(match.call())[2]
   if(is.language(.name[[1]])){
     wb_name <- sprintf("%s/%s.xlsx", path, default)
   }
   if(is.symbol(.name[[1]])) {
    wb_name <- sprintf("%s/%s.xlsx", path, as.character(.name))
   }
  wb <- loadWorkbook(wb_name, create = TRUE)
  createSheet(wb, names(.list))
  writeWorksheet(wb,.list, names(.list),header=FALSE)
  saveWorkbook(wb)
  }

the is.language/is.symbol/match.call

write_list_name(var1)

#in which case .name[[1]] is the symbol var1

write_list_name(list(n=2:3))
# in which case .name[[1]] is list(n=2:3), and class language 
# a file called list(n=2:3).xlsx would be not ideal, hence the `default` argument.
+6

@mnel, .

, :

function_name = function(input_a, input_b) {
    c = input_a * 2
    d = do_something(input_b)
    return(list(c, d))
}

input_a, input_b - , list(c, d) - . , = :

out_a = function_name(a, b)

, function_name, a b input_a input_b. , a input_a, . :

out_a = function(input_a = a, input_b = b)

, , .

+2

All Articles