Skip to main content

Section 1.4 Two rendering approaches

Merging all chapters into one Rmd file and knitting it is one way to render the book in bookdown. There is actually another way: you may knit each chapter in a separate R session, and bookdown will merge the Markdown output of all chapters to render the book. We call these two approaches β€œMerge and Knit” (M-K) and β€œKnit and Merge” (K-M), respectively. The differences between them may seem subtle, but can be fairly important depending on your use cases.
  • The most significant difference is that M-K runs all code chunks in all chapters in the same R session, whereas K-M uses separate R sessions for individual chapters. For M-K, the state of the R session from previous chapters is carried over to later chapters (e.g., objects created in previous chapters are available to later chapters, unless you deliberately deleted them); for K-M, all chapters are isolated from each other.
     1 
    Of course, no one can stop you from writing out some files in one chapter, and reading them in another chapter. It is hard to isolate these kinds of side-effects.
    If you want each chapter to compile from a clean state, use the K-M approach. It can be very tricky and difficult to restore a running R session to a completely clean state if you use the M-K approach. For example, even if you detach/unload packages loaded in a previous chapter, R will not clean up the S3 methods registered by these packages.
  • Because knitr does not allow duplicate chunk labels in a source document, you need to make sure there are no duplicate labels in your book chapters when you use the M-K approach, otherwise knitr will signal an error when knitting the merged Rmd file. Note that this means there must not be duplicate labels throughout the whole book. The K-M approach only requires no duplicate labels within any single Rmd file.
  • K-M does not allow Rmd files to be in subdirectories, but M-K does.
The default approach in bookdown is M-K. To switch to K-M, you either use the argument new_session = TRUE when calling render_book(), or set new_session: yes in the configuration file _bookdown.yml.
You can configure the book_filename option in _bookdown.yml for the K-M approach, but it should be a Markdown filename, e.g., _main.md, although the filename extension does not really matter, and you can even leave out the extension, e.g., just set book_filename: _main. All other configurations work for both M-K and K-M.