Writing
Better Organization of R Markdown Outputs
By default, the Knit button renders R Markdown output into the same folder as the source .Rmd file. The R Markdown Cookbook shows how to change that behavior by defining a custom knit function in the YAML front matter.
Using that technique, you can keep generated notebooks and reports out of the folders that hold your source code.
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 R Notebook and R Markdown outputs are saved next to the source files by default, the R code folder can become cluttered quickly. Reusing the same output filename also makes it harder to keep versions. A cleaner structure is to save dated outputs in a separate folder, 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 get there, the custom knit function needs to do three things:
- Redirect all outputs to the “R Notebook” folder.
- Replicate the relevant subfolders from “R Code” inside “R Notebook”.
- Append the date to the output filename.
The function below does all three:
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 the function from the Knit button, save it in “Include.R” and call it from the YAML front matter:
---
title: "My Beautiful Report"
date: "`r Sys.Date()`"
output: html_document
knit: (function(input, ...){ source("../Include.R"); MyRmdRender(input) })
---