0

I am quite new to R and would require some advice.

I have exported a list of dataframes final_data into excel using the following code from xlsx package:

lapply(final_data,function(x){
  write.xlsx2(x,file = "Final.xlsx",sheetName = x,append = TRUE, row.names = FALSE)
})

However, my sheet name does not reflect the name of the corresponding dataframes from the original list. Instead, the sheet name became "Sheet0", "Sheet1", "Sheet2" etc. Is there something that needs to be changed to the above code? Would greatly appreciate any advice. Thank you!

  • Did you try this? https://stackoverflow.com/questions/27713310/r-easy-way-to-export-multiple-data-frame-to-multiple-excel-worksheets – Ronak Shah May 28 '18 at 04:04
  • Is it a named list? Interesting that code does not fail as you are passing dataframe objects (not strings) into sheet name? – Parfait May 28 '18 at 04:10
  • @RonakShah Hi Ronak, yes I have tried the steps in the link, but it requires one command to append one individual dataframe to a new sheet. I was attempting to perform a loop that can do it for multiple dataframes – InvadersMustDie May 28 '18 at 05:49
  • @Parfait Hi Parfait! I am able to type `View(final_data$Product)` and it will show me the dataframe, so yes it should be a named list – InvadersMustDie May 28 '18 at 05:50
  • Try `writexl::write_xlsx` which directly writes several named sheets from a list of data frames. – meriops May 28 '18 at 07:03

1 Answers1

0

When you use lappy, you lose the information of each elements' names. So you can keep this information first, and then loop through both data and name.

library(tidyverse) 
library(xlsx)
name = names(final_data)
map2(final_data, 
     name, 
     ~write.xlsx2(.x, file = "Final.xlsx",
                  sheetName = .y, append = TRUE, 
                  row.names = FALSE))
Xinlu
  • 140
  • 5