---
title: " R : Quarto"
subtitle: "Week 12"
author:
- Menuka Bhandari
date: today
date-format: "YYYY-MM-DD"
format:
html:
theme: darkly
---R + Markdown with Quarto
Week 12 – Lecture A
1 Introduction
1.1 Overview
This session introduces the basics of Quarto - its three components YAML header, code chunks and text. You will learn to create Quarto documents, use several options to display/hide codes and figures, and render your Quarto source document to an output HTML document.
1.2 Learning goals
In this session, you will learn:
- Basics of Quarto (syntax and formats)
- How to create and render a Quarto document in RStudio
- Understand three components of Quarto ; YAML header, code chunks and text
2 Quarto
Quarto is an extension of Markdown that allows to combine prose, code, and results1. Quarto is not limited to a single programming language but can run R, Python, Julia and Observable code. Here, we will focus on using Quarto in RStudio with R.
Quarto documents are reproducible and support different output formats such as PDFs, Microsoft Word files, slide decks (presentations) and many more.
Advantages of using Quarto:
- Communicate with your collaborator: It includes code, results and steps/narrative in a single document
- Supports multi-format outputs such as HTML, PDF, Markdown, websites and more
- Reproducibility of research
Quarto is integrated into RStudio and you don’t need to install a package or anything else for basic usage.
2.1 Open a new Quarto document in Rstudio
Open a new folder for week12 by clicking the New Folder icon in the Output pane
A Quarto file is a plain text file with a .qmd extension. To create a new Quarto document: File > New File > Quarto Document

This will open a new window with several options. We can select the Quarto outputs such as Documents, Presentation, interactive in different formats. For example, for documents, we can pick HTML, PDF or Word format. Here, we will select Document and HTML format. HTML is the most useful format in Quarto.

This will create an new unamed Untitled.qmd file. Let’s rename it, by going to File, Save As and then save it as quarto_intro.qmd inside the week12 directory.
3 Rendering Quarto documents
Rendering a Quarto document converts the .qmd document to the requested format (html/pdf or any other format). During rendering, Quarto document (.qmd) is first processed using knitr, which executes code in the documents and produces a plain Markdown file, and then convert to the final format using pandoc.
So, while rendering, all code chunks are executed and their output is embedded in the final document along with the text. However, if there are any codes that produces error, your document will not be rendered.
To render a Quarto document, click on the Render button:

You can also use a keyboard shortcut to render: Ctrl-Shift-K (Windows) or Cmd-Shift-K (Mac).
There is an option to render automatically when you save. I would not personally prefer to click it because if you are doing some computationally intensive task, it will keep rendering.
View the output document: You can view the output either in a separate window, or in the Viewer pane. The gear icon next to the Render button can be used to change output viewing settings.
4 Components of Quarto documents
A Quarto document has the following three main components:
- The YAML header surrounded by (
---) - Code chunk surrounded by (```{r})
- Regular text with Markdown formatting
We’ll go over these one-by-one now.
4.1 YAML header
The header for the Quarto document is written in YAML language. It allows to specify themes, formats, executable options and many more. Additionally, it consists of series of metadata such as title, author, date etc. You can think of YAML header as the settings of the Quarto document on how to process and present your document.
It is surrounded by (---), at the top of the Quarto document. A simple example of YAML header is shown below:

We can add some additional contents to the YAML header such as authors, date, table of content and set the theme. Themes in Quarto are built on Bootstrap 5. Theme changes the visual appearance of document such as font type, color, size, code block style etc of the document. There are 25 in-built themes available for HTML in Quarto. You can even customize existing themes or create entirely new theme through Sass

Some of the additional options for the YAML header can be found here.
Project level YAML: YAML header can be specified at the project level in a file named.
_quarto.ymlin the root directory of your project. This file can be used to set default options for all Quarto documents in the project. More information about project level YAML can be found here.Document level YAML: YAML header can be specified at the document level at the top of each Quarto document. This file can be used to set options specific to that document.
There are different date formats available in Quarto.
Exercise:
Change the YAML header of your Quarto document to include the following:
- Title, subtitle, Author
- Add
date: use the formatYYYY-MM-DD - Change the
themetodarkly: Different themes are found here
Click for the solution
YAML mapping
The YAML header starts and ends with three hyphens (---). Each key-value pair should be on a new line, with a colon (:) followed by a space separating the key and value. If a value is a nested mapping, indent the nested pairs typically using two spaces per level. Keys are case-sensitive, and values can be strings, numbers, booleans, lists, or nested lists.
Self contained HTML file
HTML documents typically include a number of external dependencies (e.g., images, CSS stylesheets). By default, Quarto stores these dependencies in a separate folder within the same directory as your .qmd file. If you download or move only the rendered HTML file, the figures and other resources may not appear correctly. To generate a single, self-contained HTML file with all resources embedded, set embed-resources: true in your YAML header. This ensures that the final HTML output contains all necessary dependencies within the file itself.
YAML Sequences
A key sets of ordered variables can be specified in YAML sequences in two different ways:
- Inline syntax: Comma-separated values enclosed in square brackets (
[ ]). - Block syntax: Each item on a new line, preceded by a hyphen (
-). We saw example of block syntax in the above fig

In the above figure, we can see that html:, theme: cosmo and toc: true are nested under fotmat: key. Nesting in Quarto denotes the hierarchical relationship between options. You use nesting when you want to specify options that belong to a particular key. In this example, both theme and toc apply specifically to the HTML output. Different options are nested under their parent key using two spaces for indentation.
Quotes
In YAML, strings without special characters do not require quotes. In the above examples, although I kept the quotes around the title and author names, it is not necessary. However, quotes are necessary when string contains special characters (e.g. #, :, etc). In general, I prefer to use quotes even for strings with spaces to avoid potential errors.
The hash symbol (#) indicates the start of a comment, which is ended by the end of the line. Colon is used in YAML headers to assign values to keys.
4.2 Code chunks
Code chunks are where you write (R) code that can be executed. These are very similar to the code blocks you are already used to in plain Markdown files, except that to “enable executability”, you enclose the language indicator (r) in curly braces ({r}):

Code chunks can be added in three different ways in RStudio:
Keyboard shortcuts:
Ctrl-Alt-I(Windows) orCmd-Option-I(Mac)Typing it manually ```
{r}followed by three back ticks ``` at the end of the chunkClicking the insert button in the toolbar and select R:

Chunk options
Several options can be added to your code chunk to customize the output of code. Chunk options can be either written directly inside the curly braces or by using #| (YAML syntax) before the code chunk where each #| line sets one option. Some of the commonly used chunk options are:
echo: FALSEruns your code chunk, displays output, but does not display code in your final doc (this is useful if you want to show a figure but not the code used to create it)eval: FALSEdoes not run your code, but does display it in your final docinclude: FALSEruns your code but does not display the code or its output in your final doc
Additional chunk options are shown below:
warning: FALSEprevents warnings from showing up in your final docfig.cap:“Your figure caption” will allow you to set a figure captionfig-show=hideto hide the figures
More chunk options can be found here.
```{r eval=TRUE}
# Example code chunk
2 * 2
```[1] 4
```{r}
#| eval: true
2 * 3
```[1] 6
Global vs. chunk-specific options
If the default code chunk settings don’t fit your needs, you can change them for the whole document in the YAML section under execute:. For example, if you don’t want to show your R code to your readers, you can set echo: false which hides all code by default. If you later want to show the code for a specific chunk, you can turn it back on just for that chunk using echo: true.
Chunks can be labelled in Quarto using #| label: chunk-name before the code chunk. The chunk name should be unique and cannot contain spaces.
Advantages of labeling chunks:
- It helps to refer the chunk in other places such as cross-referencing.
- You can set up a network of certain chunks not to rerun to avoid the computational time.
```{r}
#| label: my-first-chunk
2 + 3
```[1] 5
```{r}
#| label: my-second-chunk
5 * 6
```[1] 30
Running the code chunk
There are several different options to run individual code chunks:
- Click the green play button
- Keyboard shortcut:
Ctrl-Shift-Enter(Windows) orCmd-Shift-Enter(Mac) - Place the cursor inside the chunk and press
Ctrl-Enter(Windows) orCmd-Enter(Mac)
Additional notes:
- Just like in regular R code, you can include comments inside the code chunk using the
#symbol. - Triangle sign with a line below execute all the code chunks before the current chunk.
- Triangle sign facing towards right (similar to play button) runs the current chunk.

Exercise
Add the code chunks in the Quarto document to do the following:
- Load the
tidyversepackage. Use a chunk option to hide warnings and messages while loading the package. - Read the documentation of
dplyrpackage oftidyverseusing the?operator. - Use the
diamondsdataset for this exercise. - View the
diamondsdataset usingViewfunction. Check the number of rows and column in the
diamondsdataset. Select the first 5 columns, filter carat that is greater than 0.23 and change the name of color variable to colors - Create a scatter plot using the
ggplot2package with carat inx-axisand depth iny-axis. Download the file after rendering and observe what happens when your HTML document is not self-contained. - Make your HTML document self-contained, render it, download and check the updated HTML file.
Click for the solution
## Add this in YAML `embed-resources: true`
#| warning: false
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.2
✔ ggplot2 3.5.2 ✔ tibble 3.3.0
✔ lubridate 1.9.4 ✔ tidyr 1.3.1
✔ purrr 1.1.0
── 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
str(diamonds)tibble [53,940 × 10] (S3: tbl_df/tbl/data.frame)
$ carat : num [1:53940] 0.23 0.21 0.23 0.29 0.31 0.24 0.24 0.26 0.22 0.23 ...
$ cut : Ord.factor w/ 5 levels "Fair"<"Good"<..: 5 4 2 4 2 3 3 3 1 3 ...
$ color : Ord.factor w/ 7 levels "D"<"E"<"F"<"G"<..: 2 2 2 6 7 7 6 5 2 5 ...
$ clarity: Ord.factor w/ 8 levels "I1"<"SI2"<"SI1"<..: 2 3 5 4 2 6 7 3 4 5 ...
$ depth : num [1:53940] 61.5 59.8 56.9 62.4 63.3 62.8 62.3 61.9 65.1 59.4 ...
$ table : num [1:53940] 55 61 65 58 58 57 57 55 61 61 ...
$ price : int [1:53940] 326 326 327 334 335 336 336 337 337 338 ...
$ x : num [1:53940] 3.95 3.89 4.05 4.2 4.34 3.94 3.95 4.07 3.87 4 ...
$ y : num [1:53940] 3.98 3.84 4.07 4.23 4.35 3.96 3.98 4.11 3.78 4.05 ...
$ z : num [1:53940] 2.43 2.31 2.31 2.63 2.75 2.48 2.47 2.53 2.49 2.39 ...
diamonds |>
select(1:4) |>
filter(carat > 0.23) |>
rename(colors = color)# A tibble: 53,621 × 4
carat cut colors clarity
<dbl> <ord> <ord> <ord>
1 0.29 Premium I VS2
2 0.31 Good J SI2
3 0.24 Very Good J VVS2
4 0.24 Very Good I VVS1
5 0.26 Very Good H SI1
6 0.3 Good J SI1
7 0.31 Ideal J SI2
8 0.32 Premium E I1
9 0.3 Ideal I SI2
10 0.3 Good J SI1
# ℹ 53,611 more rows
diamonds |>
ggplot(aes(carat, depth)) +
geom_point()
4.3 Markdown text
The “default text” in Quarto documents is Markdown, unlike in R scripts, where everything is considered code until commented out by #. Therefore, you can directly write regular text outside the code chunks. Quarto text syntax is based on Pandoc Markdown which is similar to original Markdown syntax we discussed in Week02
Headings
Headings are created by using # followed by a space and the heading. Quarto supports six levels of headings.
Inline code- The R code can be directly added in the text using single back ticks followed by `r`

5 Source editor vs. Visual editor
Source editor : The source editor in RStudio is is the default text editor for editing Quarto documents (.qmd files). You type everything yourself - the text, the code chunks, and the YAML settings. It gives you full control but requires knowing some Markdown and Quarto syntax. It’s good for users who like to see and control the exact code behind the document.
Visual Editor : The Quarto visual editor within RStudio provides a What You See Is What You Mean (WYSIWYM) interface for authoring Quarto documents (.qmd files). The visual editor is easier to use for the users with Microsoft Word or Google Docs background. You can format text, add images, and see how your document will look as you write. It’s great for beginners or anyone who prefers a simple, visual writing style.
You can switch between the visual editor and source editor by clicking on the Visual and Source buttons at the top right corner of the RStudio window.
Footnotes
It is the next-generation version of R Markdown, in case you have heard of that.↩︎