rdatestringrr-xlsx

How to append today's date into the filename to be saved as an Excel Workbook?


I have an R script that saves its output into an Excel Workbook.

library(stringr)
library(dplyr)
library(xlsx)

...

write.xlsx(as.data.frame(df31), file='df31.xlsx', sheetName="Sheet1", col.names=TRUE, append=TRUE)

Obviously, as per R codes above, the Excel Workbook is saved under the name of "df31.xlsx" I need to append today's date to the filename. I know that Sys.Date() will give me Today's Date.

However, I can't figure out how to add it into the codes above so that my filename turns into "df31_2021-05-20.xlsx"

Any help would be appreciated.


Solution

  • You can create filename with the help of paste0 :

    write.xlsx(as.data.frame(df31), 
              file = paste0('df31_', Sys.Date(), '.xlsx'), 
              sheetName="Sheet1", col.names=TRUE, append=TRUE))
    

    Or sprintf :

    write.xlsx(as.data.frame(df31), 
               file= sprintf('df31_%s.xlsx', Sys.Date()), 
               sheetName="Sheet1", col.names=TRUE, append=TRUE))