Quarto and it’s predecessor, R Markdown, hold code, output, tables, graphs, descriptions, interpretations, and more in a single document. While Quarto files contain R code, they can render into aesthetic, easily shared documents like pdf and html, that show as little or as much R code and output as desired. Many R textbooks, including Data Essentials With R, were written entirely with Quarto or R Markdown files. R for Data Science and Advanced R are other examples.

4.1 Quarto File Parts

New Quarto files are formatted with three parts:

  1. YAML header

  2. Markdown space

  3. Code chunks

4.1.1 YAML header

YAML headers consist of key: value pairs that control how Quarto files render or “knit” into a polished document. YAML headers determine if the Quarto file renders into a webpage (.html), flat file (.pdf), MS Word document (.docx), or other file types. Also, YAML can be added to individual code chunks to customize the appearance of code and output from those code chunks when rendering. RStudio creates YAML headers automatically when opening new Quarto files. Modifications are generally not necessary but intuitive to implement when desired.

4.1.2 Markdown Space

The white background of a Quarto file is for writing in R Markdown. In R Markdown, content and formatting commands are intermixed in the script. When the document renders though, formatting commands are executed and hidden from view.

R Markdown is one of many variations (more like a dialect) of the Markdown language. With R Markdown, we can generally write in plain English, because the formatting commands use special characters like \, $, *, [], and {}.

RStudio contains buttons (top left) to switch between a visual editor and a source editor. The visual editor hides Markdown formatting commands, shows the text content in a semi-polished appearance, and provides buttons for the most common formatting tasks, such as bold, italics, and underline.

4.1.3 Code Chunks

Code chunks interrupt the markdown space with areas for writing code. New Quarto files come pre-formatted with code chunks that demonstrate the functionality of Quarto files and the R language.

Code chunks begin and end with three backtick marks. These backticks tell RStudio to stop reading R Markdown and start reading the programming language specified inside curly braces. Here is an example:

Code
```{r}
# Below is code written in R.

print("Hello from the R Interpreter!")
x = 7
x
```
[1] "Hello from the R Interpreter!"
[1] 7

Code chunks organize an analysis into sections analogous to paragraphs of an essay. We add code chunks by one of several methods:

  1. Key shortcut: Press “option + command + i”

  2. Click the green and white +C icon above the editor pane.

  3. From the Insert pull-down menu above the visual editor pane, select “Code Chunk” and choose the programming language you wish to use.

Open a new quarto file. Add a new code chunk using the key shortcut method. Type plot(x = -5:5, y = x^2) on a blank line of code inside the chunk. With the cursor anywhere on this line of code press “command/control +”Enter”. Lastly, click “Render” above the editor pane and choose “Render HTML”.

4.2 Quarto File Setup

After opening a new quarto file, delete everything after the YAML header. With the cursor on a line below the YAML header, press “command + option + i” to insert a code chunk. Add R commands inside the code chunks and provide explanations in the Markdown space between code chunks.

4.2.1 Installing Packages

R users worldwide create and donate software packages that extend R’s utility. R packages must be installed on personal computers before use, just like any other software. Packages are installed using the “Packages” menu in the bottom right panel of RStudio, or by executing install.packages("package_name") in the R console. Do NOT include the install.packages() command inside a code chunk.

4.2.2 Loading packages (library commands)

Installed packages must be loaded in a Quarto document before use.

Note

Newer versions of RStudio often detect packages that are needed but not installed. RStudio produces a message related to the uninstalled packages and provides an install option if the packages are available in online repositories.

Loading packages is performed with the library() command, as shown below. Before writing other code, we often load staple packages like tidyverse() and knitr(). The tidyverse package contains features for importing, modifying, and summarizing tibbles and dataframes. Knitr is a package that provides tools for rendering documents. KableExtra is a package that produces tables formatted for presentation or publication.

Code
library(knitr)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.5.1     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.1
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
Code
library(kableExtra)

Attaching package: 'kableExtra'

The following object is masked from 'package:dplyr':

    group_rows

Notice from the output that when a package is first loaded, R indicates the load was successful and identifies new commands that override or “mask” existing commands from base R or other packages.

4.2.3 Loading multiple packages (p_load)

The p_load command from the pacman package can load multiple packages simultaneously. Also, add #| warning: false to the top of a code chunk to avoid showing unimportant messages and warnings in the rendered document. Alternatively, add #| echo: false, and both the code and output will disappear from the rendered document.

Code
```{r}
#| warning: false
pacman::p_load(knitr, tidyverse, kableExtra)
```

4.3 Markdown formatting

With RStudio’s visual editor, learning R Markdown is not necessary. The visual editor provides formatting buttons and hides the formatting characters intermixed with content. However, switching to the source editor reveals the formatting characters, which are generally easy to interpret and modify.

4.3.1 Hashtags in R Markdown

Hashtags followed by a single space have three useful features in R Markdown:

4.3.1.1 Feature 1 - Collapsible document sections

Hashtags followed by a space create collapsible sections of the R Markdown file. Notice the small gray arrow to the left of the hashtags above. Click on the arrow a few times to see what happens. Large sections of the Markdown document collapse into a single line, leaving only the text that follows the hashtag visible as a header. Headers with more hashtags nest within headers with fewer hashtags. Script files that are hundreds of lines can collapse to a small number of headers that serve as an outline for the entire document.

4.3.1.2 Feature 2 - RStudio navigation outline

Hashtag headers in the Markdown space create a separate outline, viewable by clicking the Outline button above the editor pane and expanding the side window that opens. Clicking within the outline moves the editor to that part of the document.

4.3.1.3 Feature 3 - Rendered document headers and navigation outlines

Hashtag headers appear in a larger, darker font when rendered. One hashtag creates the most prominent header (like for “Quarto Basics”). Level 1, 2, and 3 headers also become navigation outlines that appear in a side panel of a rendered document like this one.

WARNING Hashtags & spaces

The space after the hashtag is critical. Notice how the text below lacks a space after the hashtags and appears in the rendered document as regular text rather than a level 4 header.

####Not a level 4 header because a space is missing after the hashtags.

4.3.2 Use headers to organize documents

Think of a Quarto file as an instruction manual or text book with big units indicated by a single hashtag, chapters by two hashtags, chapter subsections by three hashtags, etc.

4.3.3 More Markdown Features

See the online Quarto Markdown Basics documentation.

4.3.4 Rendering (Knitting)

From the visual editor, the “Render” pull-down menu provides options to produce the polished document as a .html, .pdf, or .docx file. Select one of these options now. If the render fails, read the error messages and try to fix the problem. Often this means installing additional packages called dependencies.