1

I have 2 data frames that I would like to export to Excel, with each dataframe on a different worksheet, and to title each sheet.

I have tried the following with write.xlsx .

Here is the list of my 2 data frames followed by the title I would like to give them in the new Excel workbook:

list_of_datasets <- list(pivot.diagnosis, stat.pivot.quarter)
wk.title <- c("9-STD Durations", "10-STD Clinical Categories")

This is the loop I have tried:

for (i in length(list_of_datasets)) {
  write.xlsx(list_of_datasets[i], file = "Trial.xlsx", 
           sheetName = wk.title[i], 
           append = TRUE)
}

PROBLEM: This only outputs the last data frame (i.e. stat.pivot.quarter) to the Trial.xlsx spreadsheet. Append = TRUE is there, so I would think it would append with each iteration of the loop, but it's not. It seems like append = T isn't working

Any leads appreciated!

actuary
  • 33
  • 4
  • There are a couple of packages that write to excel, which one are you using? – akash87 Dec 12 '19 at 21:49
  • Also, for a list, you are going to need to use `write.xlsx(list_of_datasets[[i]], file = "Trial.xlsx"` – akash87 Dec 12 '19 at 21:53
  • Potential duplication of [this question](https://stackoverflow.com/questions/27524472/list-of-data-frames-to-individual-excel-worksheets-r) or [this one](https://stackoverflow.com/questions/27713310/easy-way-to-export-multiple-data-frame-to-multiple-excel-worksheets) – Ben Dec 12 '19 at 21:54
  • 1
    To clarify, my code was for _only_ 2 data frames, but I am really interested in doing this for _many_ data frames. Particularly interested in _custom naming_ each worksheet as the loop exports each data frame. Thx – actuary Dec 13 '19 at 01:33

1 Answers1

0

writexl is a lightweight package that would serve you well here.

writexl::write_xlsx(
  list("sheetname1" = dataframe1, "sheetname2" = dataframe2),
  path = "path/to/save/to.xlsx"
)
Fleur De Lys
  • 480
  • 2
  • 9
  • 1
    This is not helpful. I was using this package already - see my code above. I need a loop for many data frames, and be able to loop through and place unique worksheet names for each iteration/data frame. – actuary Dec 13 '19 at 01:22