B.2 R Markdown

Thanks to the power of R and Pandoc, you can easily do computing in R Markdown documents, and convert them to a variety of output formats, including HTML/PDF/Word documents, HTML5/Beamer slides, dashboards, and websites, etc. An R Markdown document usually consists of the YAML metadata (optional) and the document body. We have introduced the syntax for writing various components of the document body in Chapter 2, and we explain more about the YAML metadata in this section.

Metadata for R Markdown can be written in the very beginning of a document, starting and ending with three dashes ---, respectively. YAML metadata typically consists of tag-value pairs separated by colons, e.g.,

---
title: "An R Markdown Document"
author: "Yihui Xie"
---

For character values, you may omit the quotes when the values do not contain special characters, but it is safer to quote them if they are expected to be character values.

Besides characters, another common type of values are logical values. Both yes and true mean true, and no/false mean false, e.g.,

link-citations: yes

Values can be vectors, and there are two ways of writing vectors. The following two ways are equivalent:

output: ["html_document", "word_document"]
output:
  - "html_document"
  - "word_document"

Values can also be lists of values. You just need to indent the values by two more spaces, e.g.,

output:
  bookdown::gitbook:
    split_by: "section"
    split_bib: no

It is a common mistake to forget to indent the values. For example, the following data

output:
html_document:
toc: yes

actually means

output: null
html_document: null
toc: yes

instead of what you probably would have expected:

output:
  html_document:
    toc: yes

The R Markdown output format is specified in the output field of the YAML metadata, and you need to consult the R help pages for the possible options, e.g., ?rmarkdown::html_document, or ?bookdown::gitbook. The meanings of most other fields in YAML can be found in the Pandoc documentation.

The rmarkdown package has provided these R Markdown output formats:

  • beamer_presentation
  • context_document
  • github_document
  • html_document
  • ioslides_presentation
  • latex_document
  • md_document
  • odt_document
  • pdf_document
  • powerpoint_presentation
  • rtf_document
  • slidy_presentation
  • word_document

There are many more possible output formats in other R packages, including bookdown, tufte, rticles, flexdashboard, revealjs, and rmdformats, etc.