Statistics, Science, Random Ramblings

A blog mostly about data and R

Dynamic output names with RMarkdown

Posted at — Oct 31, 2019

Thanks to an answer on Stack Overflow I just learned that there is a nifty way to have dynamic output file names when using RMarkdown in RStudio.

My situation is that I want to keep a few Rmd files which I adapt from time to time, but I also want to keep older outputs around. Thanks to version control the first part is not much of an issue, but the second part is a bit more tricky as the default output when knitting a RMarkdown document is to just overwrite the previous output.

However, you can add a knit YAML header specifying the exact command that is called when you click RStudio’s knit button, like so:

knit: (function(inputFile, encoding) { 
        inputFile, encoding = encoding, 
        output_file = file.path(
            dirname(inputFile), paste0(Sys.Date(), '_my_summary.html'))) 

Using Sys.Date() for the output file name will lead to having one output file per day, but you can specify pretty much anything you like here.