0

I'm trying to write data from my for loop to excel file in a way that the data is in one sheet. I've been using the xlsx library but for some reason adding the APPEND = TRUE doesn't do the trick. An example of what I've been trying to do:

write.xlsx("Info", "results.xlsx", sheetName="Info", col.names=TRUE, row.names=TRUE, append=FALSE)

for (i in 1:10) {
  write.xlsx(i, "results.xlsx", sheetName="datasheet",col.names=TRUE, row.names=TRUE, append=TRUE)
}

This only works to write the first loop results, after that I get an error telling me that there's already a sheet with the same name and it won't append the result to the sheet. How should I approach this?

Orion
  • 65
  • 1
  • 9
  • Have you tried writing to different sheetName's? – Florian Jun 08 '20 at 08:35
  • @Florian My point is that I want the results to be displayed in one sheet. Using multiple sheets would be easy, but in reality my code would do a loop around 10 000 times and then push the results into a excel file, after that I need to be able to view the results easily. – Orion Jun 08 '20 at 08:41
  • Do you need to write the results 10 times to excel? Why not store it in a list or a dataframe, combine it into one data frame at the end and write is using `write.xlsx` ? – Ronak Shah Jun 08 '20 at 08:44
  • @RonakShah The way rest of the code works the best way would be to append the results after each loop - of course if there's no way of doing this I would have to try this. – Orion Jun 08 '20 at 08:56

1 Answers1

1

have you tried saving your output and then write it in one go (not fast!)?:

i0 <- NULL
    for (i in 1:10) {
    i0 <- rbind(i0,i)
    }
    write.xlsx(i0, "results.xlsx", sheetName="datasheet",col.names=TRUE, row.names=TRUE)

see also: Appending r output in a single sheet of xlsx file

efz
  • 425
  • 4
  • 9