Chapter 4 Templates

  1. Built-in templates
  2. Templates from R packages
  3. User-defined templates

4.1 Built-in templates

R Markdown has several built-in output templates that you just have to specify them with the YAML output option. These include:

  • Documents
    • html_document
    • pdf_document
    • word_document
  • Presentations
    • ioslides_presentation and slidy_presentation for HTML
    • beamer_presentation for PDF
    • powerpoint_presentation
  • Interactive Shiny documents and presentations

4.2 Templates from R packages

You can also download specific templates from CRAN or GitHub. You use them the same way as the built-in templates by specifying them in the YAML header. A few that I’ve used or played with include:

4.3 User-defined templates

There are also ways to include templates for other output types in the YAML header.

4.3.1 PDF

For PDFs, you can include LaTeX templates, but you need to pay attention to the use of $. The PLOS template referenced in the example below failed to compile when I first downloaded it, because $ are special characters for pandoc. After I added a second $ throughout the document (just using find and replace), it worked.

---
output:
  pdf_document:
    template: plos_latex_template.tex
---

See Section 6.4.1 for calling specific LaTeX packages in R Markdown.

4.3.2 Word

You can also set up Word templates. To do this, you need to use the Styles Pane in the Word Document you want to use as a template. Highlight the text you want to format, make the desired changes, then find the style that applies to that section, and find Update to Match Selection in the dropdown menu.

In the example below, you can see that I’m editing the Header 1 format, so I need to update that particular entry in the Styles Pane. I like to check the Show styles guide option at the bottom of the Styles Pane, which filters the list of styles to just the ones used in the document and marks them in the document.

You have to go through this editing process for every text element in the document, but once you’ve set it up, you can simply include it in the YAML header.

---
output:
  word_document:
    reference_docx: template.docx
---