15.6 Using bookdown

The bookdown package (Xie 2020a) is designed for creating long-form documents with multiple R Markdown documents. For example, if you want to write a book, you can put each chapter in its own Rmd file.

For RStudio users, the easiest way to get started is to create a bookdown project from File -> New Project -> New Directory -> Book Project using bookdown, as you can see from Figure 15.2.

Create a bookdown project in RStudio.

FIGURE 15.2: Create a bookdown project in RStudio.

To demonstrate the usage, we provide a minimal example consisting of three files within the same directory:

directory
  |- index.Rmd
  |- 01-intro.Rmd
  |- 02-analysis.Rmd

Below we show the content of each file and explain their roles.

  • index.Rmd:
---
title: "A Minimal bookdown Project"
site: bookdown::bookdown_site
output: bookdown::gitbook
---

# Preface {-}

Some content

The first file is typically called index.Rmd. It should be the only Rmd file in which you provide the YAML frontmatter. It should also include a special YAML field site: bookdown::bookdown_site, so that rmarkdown knows to use bookdown to build all Rmd files, instead of rendering a single Rmd file. You can use any bookdown output formats, such as bookdown::gitbook, bookdown::pdf_book, bookdown::word_document2, and bookdown::epub_book.

The next two Rmd files are two chapters:

  • 01-intro.Rmd:
# Chapter 1

This is chapter 1.
  • 02-analysis.Rmd:
# Chapter 2

This is chapter 2.

To render these Rmd files, you should call bookdown::render_book('index.Rmd') instead of rmarkdown::render(). Under the hood, bookdown merges all Rmd files into a single Rmd by default and compile it. Files are merged in the alphabetical order. That is why we added numeric prefixes to filenames in the above example.

There are a lot of settings that you can customize for a bookdown project. For a more comprehensive overview of bookdown, you may see Chapter 18 the rmarkdown book (Xie, Allaire, and Grolemund 2018). For the full documentation, see the bookdown book (Xie 2016).

References

Xie, Yihui. 2016. Bookdown: Authoring Books and Technical Documents with R Markdown. Boca Raton, Florida: Chapman; Hall/CRC. https://github.com/rstudio/bookdown.

Xie, Yihui. 2020a. Bookdown: Authoring Books and Technical Documents with R Markdown. https://github.com/rstudio/bookdown.

Xie, Yihui, J. J. Allaire, and Garrett Grolemund. 2018. R Markdown: The Definitive Guide. Boca Raton, Florida: Chapman; Hall/CRC. https://bookdown.org/yihui/rmarkdown.