How to combine two RMarkdown (.Rmd) files into a single output?

August, 2018 update: This answer was written before the advent of bookdown, which is a more powerful approach to writing Rmarkdown based books. Check out the minimal bookdown example in @Mikey-Harper’s answer!

When I want to break a large report into separate Rmd, I usually create a parent Rmd and include the chapters as children. This approach is easy for new users to understand, and if you include a table of contents (toc), it is easy to navigate between chapters.

report.Rmd

---  
title: My Report  
output: 
  pdf_document:
    toc: yes 
---

```{r child = 'chapter1.Rmd'}
```

```{r child = 'chapter2.Rmd'}
```

chapter1.Rmd

# Chapter 1

This is chapter 1.

```{r}
1
```

chapter2.Rmd

# Chapter 2

This is chapter 2.

```{r}
2
```

Build

rmarkdown::render('report.Rmd')

Which produces:
My report

And if you want a quick way to create the chunks for your child documents:

rmd <- list.files(pattern = '*.Rmd', recursive = T)
chunks <- paste0("```{r child = '", rmd, "'}\n```\n")
cat(chunks, sep = '\n')
# ```{r child = 'chapter1.Rmd'}
# ```
#
# ```{r child = 'chapter2.Rmd'}
# ```

Leave a Comment