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

knitrpandocrr-markdown

I have two files in the same folder: chapter1.Rmd and chapter2.Rmd, with the following content:

chapter1.Rmd

---
title: "Chapter 1"
output: pdf_document
---

## This is chapter 1. {#Chapter1}

Next up: [chapter 2](#Chapter2)

chapter2.Rmd

---
title: "Chapter 2"
output: pdf_document
---

## This is chapter 2. {#Chapter2}

Previously: [chapter 1](#Chapter1)

How can I knit these so that they combine into a single pdf output?

Of course, render(input = "chapter1.Rmd", output_format = "pdf_document") works perfectly but render(input = "chapter1.Rmd", input = "chapter2.Rmd", output_format = "pdf_document") does not.

Why do I want to do this? To break up a giant document into logical files.

I've used @hadley 's bookdown package to build latex from .Rmd but this seems like overkill for this particular task. Is there a simple solution using knitr/pandoc/linux command line I'm missing? Thanks.

Best Answer

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'}
# ```
Related Topic