rr-markdownknitr

How do I prevent compilation of a child Rmd document, compiling a root document instead?


I like to include child Rmd documents from a main Rmd document when drafting "big" papers, because this helps me divide work up and also prevents conflicts when multiple people are working on the same paper but different sections. However, I often absent-mindedly hit "knit" to compile the main Rmd when I have the child document open, which creates a stray HTML document that contains only that section, which is not what I want: I'd want the "knit" button to compile the main document.

For instance, consider a folder containing main.Rmd:

---
title: "Untitled"
output: html_document
---

This is the main document.

```{r child="child.Rmd"}
```

...and child.Rmd:

This is the child document.

I know TeX has a special comment you can put in a child that sets the "TeX root": https://www.texdev.net/2011/03/24/texworks-magic-comments/

"[The magic comment TeX root] [i]ndicates that the current file is not the main file for typesetting: when you choose to typeset, TeXworks will save the current file then typeset the master file. Using this setting, you need the full name of the master file including the extension. This is clearly a handy setting for larger projects, where you might have a lot of files which are to be included in one master document."

What I've been doing is to include the following YAML header on all child documents (e.g., child.Rmd above):

---
output: 0
editor_options: 
  chunk_output_type: console
---

The output: 0 line prevents compilation, since "0" is not the name of a valid output function.

This prevents stray HTML files from being created, since the document will not compile by itself (and the header seems to be ignored in child documents).

However, it would be nice to have a solution like TeX root, where it points to the main document and compiles that. Is there a way to do this formally, or to hack it together?

I've tried this:

---
output: "\\(...) rmarkdown::render('path/to/main.Rmd',...)"
editor_options: 
  chunk_output_type: console
---

...and this (surprisingly) seems to compile the main Rmd, but I get the error

Output created: main.html
Error: Format is not of class rmarkdown_output_format
Execution halted

My questions are these:


Solution

  • I don't know if your approach will have bad side effects, but there's a standard way to do the same thing: use the knit: YAML entry described here.

    What you would do is put this line into the YAML of the child documents, and the main document would be knitted instead:

    knit: (\(input, ...) rmarkdown::render('mainfile.Rmd',...))
    

    This assumes you are using RStudio and clicking on the Knit button. If you explicitly call rmarkdown::render() on the child document, only it will be rendered.