Chapter 2 Parts of a document

  1. YAML header
  2. Markdown
  3. Code chunks

2.1 YAML header

The first part of your document is called the YAML (which cheekily stands for YAML Ain’t Markup Language) header. The YAML header goes at the very top of your document, and is where you set global options for output type and formatting. This header is set apart from the rest of the document by three dashes, as shown in the example below.

---
title: "Why R Markdown Is the Best"
author: "Me"
output: html_document
---

Section 6.2 has more information on setting YAML formatting parameters.

2.2 Markdown

The plain text-formatting syntax of R Markdown allows for conversion to different document types. In the example below, the # denotes a header, while the numbered list behaves like you would expect one to in Word. However, unlike Word, the actual numbers don’t matter; as you can see, I’ve included all 1’s here, but it will render as an appropriately-numbered list.

# Parts of a document

1. YAML header
1. Markdown
1. Code chunks

Go to Chapter 5 for more information on markdown syntax.

2.3 Code chunks

Code chunks are one of the core features of R Markdown. Code chunks are set apart from markdown by three backticks at the beginning and end.

In curly brackets after the first set of backticks, you specify the coding language you want to use (here, it’s R, with a lowercase r). You can also add other arguments in the curly brackets, like a name for the chunk (here, it’s setup), and specific chunk options.

The example I’ve provided below would be the first chunk in an R Markdown document. It establishes the default chunk options with knitr::opts_chunk$set. You can see that while I’ve set echo = TRUE globally, so that all of my code chunks appear in the document by default, I set echo = FALSE for this specific chunk. A full list of chunk options can be found here.

```{r setup, echo = FALSE}
## Set-up ##

knitr::opts_chunk$set(echo = TRUE)

## Load packages ##

# Package list
pkg_list <- c("plyr","tidyverse", "data.table", "ggplot2", "kableExtra", 
              "psych", "Rmisc", "patchwork")

# Load packages
pacman::p_load(pkg_list, character.only = TRUE)
```

There are multiple ways to run code chunks to test them in RStudio before creating your output. You can run code like you would in R by highlighting the relevant lines of code and hitting CTRL/command + enter. You can also hit the green play button in the upper right-hand corner of the chunk.

Each chunk is an island, so if you haven’t run a previous chunk that contains some variable you need in the chunk you want to run, it’ll throw an error. At the top right of your open .Rmd document in RStudio, you’ll also see a Run dropdown menu. There, you can choose different options for running certain code chunks.

Tip: you can use the chunk option cache = TRUE for very time-consuming chunks, but there are some caveats as described here.