How to pass dataframe name to Excel worksheet (using xlsx package)

I'm trying to use lapply to go through a list of data frames and execute a custom function for each. In this function, I am trying to name the worksheet (using xlsx) according to the dataset name. Is it possible? Example:

myList <- list(DataFrame1, DataFrame2, DataFrame3, DataFrame4)

require(xlsx)
export <- createWorkbook()

lapply(myList,
       ExcelExport <- function(dataset) {

nameDF <- deparse(substitute(dataset))

# Use another function and store the output               
DF <- as.data.frame(function2(dataset)) 
# Here is where I'm having trouble naming the worksheet according to the name of the Dataframe:               
wksht <- createSheet(wb=export, sheetName = paste("Dataset is ", nameDF, sep = ""))  
               addDataFrame(x=DF, sheet = wksht)


)
# Save it to an excel file (either existing or new) under a given name
saveWorkbook(export, "Export1.xlsx")

      

I found deparse(substitute())

from Getting the name of a dataframe , but it seems like renaming my dataframe to X[[i]]

, which then throws an invalid character error for '['

+3


source to share


1 answer


Here's the edited code that allows you to refer to the names of the list nodes. Please check your code before posting, it contains some ambiguities.



myList <- list(DataFrame1 = data.frame(matrix(rnorm(100), 10, 10)), 
               DataFrame2 = data.frame(matrix(rnorm(100), 10, 10)), 
               DataFrame3 = data.frame(matrix(rnorm(100), 10, 10)), 
               DataFrame4 = data.frame(matrix(rnorm(100), 10, 10)))

require(xlsx)
export <- createWorkbook()

lapply(seq_along(myList), function(i) {
  ExcelExport <- function1(myList[[i]]) # Your code was incomplete here
  # You don't have object 'ExcelExport' anywhere esle in your code
  # so this step seems useless...

  # Now you have a full access to myList inside lapply 
  nameDF <- names(myList)[i]

  # Use another function and store the output               
  DF <- as.data.frame(function2(myList[[i]])) 

  wksht <- createSheet(wb=export, sheetName = paste("Dataset is ", nameDF, sep = ""))  
  addDataFrame(x=DF, sheet = wksht) # Btw, object 'wksht' is not defined in your code

})
# Save it to an excel file (either existing or new) under a given name
saveWorkbook(export, "Export1.xlsx")

      

0


source







All Articles