Chapter 7 Organization

If you’re working on a large R Markdown project, like a thesis, it’s inevitable that you will have several code chunks to perform pieces of one process (e.g., reformatting data for plotting and then creating the plots), and you will have lots of chapters/sections of markdown.

At a minimum, you want to keep your chunks small and name them for easy troubleshooting. Also, use headers at multiple levels, which makes it easier to navigate your document.

One thing to note is that you cannot have the same chunk names anywhere in your document or sub-documents; this will throw an error. If you go to the bottom left-hand corner of your .Rmd file in RStudio, you’ll see a small drop-down menu. There, you can jump to specific headers and code chunks.

As your documents grow, even these sections will become difficult to keep straight. This is when you want to use child documents and source scripts.

I created an R Markdown template for reproducible scientific manuscripts if you are interested in seeing this organizational structure in action.

7.1 child documents

All you have to do is make a code chunk in which you set the child parameter equal to the file that you want to reference (and file path if it’s in a subfolder). The chunk itself must be empty, as shown in the example below.

```{r child = 'path/child_doc.Rmd'}
```

One thing to note when you’re testing your code (that is, not rendering the whole document): if you run a code chunk that references a child document, it will not run the code in the referenced document. You have to open the child document in RStudio and run all of the chunks manually before continuing with the rest of the chunks in the main document.

7.2 Sourcing code

You can use the source function to import all of the code from an R script like you would for a child document.

source("path/script.R")