Back to Homepage


Better Organization of RMarkdown Outputs

Feng Jiang
Last Updated: 2020-11-19

By default, knit renders RMarkdown outputs to the same folder of the .Rmd file. The RMarkdown Cookbook demonstrates that the behavior of the Knit button can be changed by defining the custom knit function in the YAML frontmatter.

Based on the technique, this post will show you how to improve the organization of the RMarkdown outputs in your project.

Suppose your project is organized with the following folder structure:

Project\
 + Documents\
 + R Code\
   + Project.Rproj
   + Include.R
   + 1 Load\
     + 11 Load Student Data.Rmd
     + 11 Load Student Data.nb.html
     + 12 Load School Data.Rmd
     + 12 Load School Data.nb.html
   + 2 Calculation\
   + 3 Check\
 + R Data\
 + Raw Data\
 + Results\

Because the R Notebook / RMarkdown outputs are saved in the same folder as the source code files by default, it makes the R code folder cluttered with too many files. Also, having all the outputs under the same name is not good for versioning. Sometimes we want the outputs to be dated. So ideally, we want the files to be organized like this:

Project\
 + Documents\
 + R Code\
   + Project.Rproj
   + Include.R
   + 1 Load\
     + 11 Load Student Data.Rmd
     + 12 Load School Data.Rmd
   + 2 Calculation\
   + 3 Check\
 + R Data\
 + R Notebook\
   + 1 Load\
     + 11 Load Student Data - 2020-11-18.html
     + 11 Load Student Data - 2020-11-20.html
   + 2 Calculation\
   + 3 Check\
 + Raw Data\
 + Results\

To achieve this, we need to do three things to the RMarkdown output:

We can get all these done in a few lines:

MyRmdRender = function(input)
{
    subdir = basename(getwd())
    rmarkdown::render( input, 
                       output_file = paste0( gsub(".Rmd","",input), " - ", Sys.Date() ), 
                       output_dir = paste0("R Notebook/", subdir), 
                       envir = globalenv() )
}

To use this custom function in knit, just put it in "Include.R" and then call it from the YAML frontmatter:

---
title: "My Beautiful Report"
date: "`r Sys.Date()`"
output: html_document
knit: (function(input, ...){ source("../Include.R"); MyRmdRender(input) })
---

© 2020 fengjiang.me