During the course of a project, you may want to repeat a similar analysis across multiple R Markdown files. To avoid duplicated code across your files (which is difficult to update), there are multiple strategies you can use to share common code:
To share R code like function definitions, you can put this code in an R script and import it in each file with the function
To share common R Markdown text and code chunks, you can use child documents
To share common templates, you can use the function
Each of these strategies is detailed below, with a special emphasis on how to use them within the workflowr framework. In order to source scripts or use child documents, it is suggested you use the here package, which helps to locate the root directory of your project regardless of the directory your script or analysis file is, making sourcing documents cleaner.
First, a quick overview of the directories in a workflowr project. This is critical for importing these shared files.
In a standard R Markdown file, the code is executed in the directory where the R Markdown file is saved. Thus any paths to files in the R Markdown file should be relative to this directory. However, the directory where the code is executed, referred to as the “knit directory” in the workflowr documentation, can be configured. The default for a new workflowr project is to run the code in the root of the workflowr project (this is defined in the file
?wflow_html for configuration details). Thus any filepaths should be relative to the root of the project. As an example, if you have shared R functions defined in the file
~/Desktop/myproject/code/common.R, the relative filepath from the root of the project directory would be
The reason for this is very technical and requires more understanding of how workflowr is implemented than is necessary to use it effectively in the majority of cases. Whenever workflowr builds an R Markdown file, it first copies it to a temporary directory so that it can inject extra code chunks that implement some of its reproducibility features. The figures in the child documents end up being saved there and then lost.↩︎
knitr::knit(), you’ll need to load the dplyr and ggplot2 packages to run the code in this example child document.↩︎