Search code examples
rgt

Auto Add Month and Year within gtsave()


I am working on a project that requires monthly data analysis for surveillance cycles. However, I won't be around every month and am trying to set up a QMD that will help to steamline and automate the data analysis process (as much as it can be automated). For the last step, I am trying to add a section where all graphics are saved using gtsave() with their object name, followed by _monthyear (_072024).

Below is a snipped of my code meant to emulate this problem.

gt::gtsave(Table1, 
           filename = "...filepath/Table1_072024.png")

gt::gtsave(Table2, 
           filename = "...filepath/Table2_072024.png")

....

What I am trying to figure out is if there is some code that I can add to the gtsave() that will automatically change the month and date without the user having to manually enter them for each object. I'm not sure if this is possible but I appreciate any tips or suggestions that you all may have!

Thanks!


Solution

  • You can use the format function to format a date into any format you need, then use that formatted date in your file path:

    date <- Sys.Date()
    
    date
    #> [1] "2024-07-23"
    
    text_date <- format(date, "_%m%Y")
    
    text_date
    #> [1] "_072024"
    
    paste0("...filepath/Table2", text_date, ".png")
    
    #> [1] "...filepath/Table2_072024.png"
    
    gt::gtsave(Table1, 
               filename = paste0("...filepath/Table1", text_date, ".png"))
    
    gt::gtsave(Table2, 
               filename = paste0("...filepath/Table2", text_date, ".png"))