
3 Introduction to Quarto
Quarto is an authoring framework that seamlessly integrates text, computer code, and output (e.g., in the form of data visualization) into a cohesive document. We will use Quarto extensively throughout this book because it is free, open-source, supports multiple programming languages (e.g., R, Python, and SQL), and seamlessly integrates into RStudio. When a Quarto document is rendered, the output reflects the latest versions of the data and code. Additionally, Quarto supports diverse output formats, including HTML, PDF, and Word. Because of its adaptability, Quarto is an invaluable addition to the toolbox of every contemporary data scientist. This chapter covers the essential features of Quarto required throughout this book.
Section 3.1 will demonstrate how to create a new, blank Quarto document using RStudio before Section 3.2 will outline the general structure of a Quarto Markdown (QMD) file. Section 3.3 and Section 3.4 will continue with an exploration of QMD’s two primary building blocks: marked-up text and code chunks.
3.1 Creating a New Quarto Document
To initiate a basic Quarto template, you need to start an RStudio project, navigate to the File menu, and select “Quarto Document” from the “New File” context menu. This action opens the dialog window shown in Figure 3.1, where the document’s title and author name can be entered. This information will later appear at the top of the rendered document. From the available output formats, I recommend choosing HTML because the rendered document can be viewed with any standard web browser, whereas the PDF and Microsoft Word formats both require additional software (\(\LaTeX\) and a word processor, respectively). Additionally, ensure that Knitr is chosen as the engine, and untick the box “Use visual markdown editor.”
To create a new Quarto document, go to File \(\rightarrow\) New File \(\rightarrow\) Quarto Document.

After clicking “Create Empty Document,” a new tab appears in the editor pane at the top left of the RStudio window. Please ensure that the Source tab, not the Visual tab, is selected just above the editor pane.1 At this point, there are only four lines of code, shown in Figure 3.2. If your editor contains more than these lines, please edit the code to resemble the display in Figure 3.2.

The Quarto document currently consists of only a header, sandwiched between two lines containing three hyphens each (---
). The header is written in YAML, a recursive acronym for “YAML Ain’t Markup Language.” Authoring Quarto documents does not require deep YAML knowledge. It suffices to know that each entry in a YAML header is a key-value pair, separated by a colon. For example, the title or the author can be changed by editing the corresponding values in the YAML header. It is possible to add keys beyond title
and author
, such as subtitle
and date
. A comprehensive list of YAML keys for HTML output and their possible values is available on the Quarto website.
The YAML header of a Quarto Markdown (QMD) file consists of key-value pairs in the format key: value
.
You can save the current file using either the menu (File \(\rightarrow\) Save) or the keyboard shortcut Control-SControl-S (Windows and Linux) or Command-SCommand-S (Mac). When naming the file, the extension should be .qmd
, which stands for “Quarto Markdown.” If the extension is omitted, RStudio will automatically append it.
QMD files have the extension .qmd
.
Next, click the Render button in the toolbar above the editor pane (Figure 3.2). Alternatively, use the keyboard shortcut Shift-Ctrl-KShift-Ctrl-K (Windows and Linux) or Shift-Command-KShift-Command-K (Mac). RStudio will then automatically open a browser window to display the rendered website, as shown in Figure 3.3.
The process of converting a QMD file to a reader-friendly format, such as HTML, is called rendering.

3.2 Structure of a Quarto Document
Following the YAML header at the top, QMD files consist of a mixture of text and code chunks, as illustrated in Figure 3.4. The text is written in Markdown, a markup language known for its simplicity and readability, which you will learn in Section 3.3. Code chunks in a QMD file can be written in various programming languages, such as R, Python, and SQL. During the rendering process, Quarto executes the code chunks in the order they appear in the QMD file, incorporating their results into a reader-friendly document. Depending on the options chosen by the user for each code chunk, the code itself and the output may be displayed in the rendered document. Section 3.4 will introduce some of the available execution options for code chunks.
QMD files contain a mixture of text, written in the Markdown language, and code chunks.

3.3 Marked-Up Text
You are probably familiar with word processors, such as Microsoft Word or Google Docs, which operate on the principle of “What You See Is What You Get” (WYSIWYG). For instance, if you want to display parts of a text in boldface using word processing software, you need to highlight the text, navigate through menu options (e.g., in Word: Format \(\rightarrow\) Font), and use drop-down menus to select a bold font weight. Afterward, the text appears in bold on the computer screen. The WYSIWYG method provides immediate visual feedback about the document. However, when opening the file using another word processor, the text may not appear identical due to differences in the software implementation.
An alternative to WYSIWYG is offered by markup languages. In a markup language, users insert special character sequences into the text to indicate how they want the text to appear. As a result, the source text does not immediately resemble the rendered document because the symbols appear in the source file alongside the text. The advantage of using a markup language is that different software can consistently interpret the user’s intention. An example of a markup language is the HyperText Markup Language (HTML), used for writing websites. When viewing an HTML document, the result is a consistently formatted website, regardless of the web browser used.
Markdown is a markup language that was developed by Gruber (2004) and Swartz (2004) with the intention of being simple to learn and easy to read. It is supported by many applications, including RStudio and GitHub. Quarto follows the same rules as Markdown for rendering plain text and adds a few additional features that allow users to include computer code.
Markdown uses special character sequences to indicate how text should be formatted.
This section will introduce you to the basic features of Markdown. Section 3.3.1 will explain how to format blocks of text, such as sections, paragraphs, and lists. Section 3.3.2 will then demonstrate how to add formatting within a block of text (e.g., to emphasize key words). Section 3.3.3 will introduce you to the basics of code rendering, either as a separate block or inline (i.e., within text). Section 3.3.4 will demonstrate how to insert special characters, reserved by Markdown to mark up text, into your document. Finally, Section 3.3.5 will explain how to include raw HTML code in your Markdown document, serving as a last resort if no native Markdown solution is available.
3.3.1 Text Blocks
A text block is a sequence of words treated as a unit. This section covers four important types of text blocks: sections (Section 3.3.1.1), paragraphs (Section 3.3.1.2), lists (Section 3.3.1.3), and block quotes (Section 3.3.1.4).
3.3.1.1 Section Headings
Markdown text is typically rendered verbatim in the output, with a few exceptions. For instance, section headings always start with one or several hash symbols (#
) followed by a space; however, neither the hash symbol nor the space appear verbatim in the rendered document. Instead, the number of hash symbols (between 1 and 6) determines the level of the heading and, consequently, the appearance of the title in the rendered document, as demonstrated in the following example and Figure 3.5:
# Top-Level Heading
## Second Level
### Third Level
#### Fourth Level
##### Fifth Level
###### Sixth Level
Use #
for a first-level heading, ##
for a second-level heading, and so on.

3.3.1.2 Paragraph Breaks and Forced Line Breaks
Line breaks in a Markdown file do not necessarily translate into line breaks in the output. To indicate a break between paragraphs, you must insert a blank line in the Markdown text.
Use a blank line to separate paragraphs.
To indicate a line break inside a paragraph, you can end the line with two spaces. Alternatively, you can enforce a line break
using a backslash.
Here is the previous paragraph written in Markdown. Please note that there are two invisible spaces after end
on the first line:
At the end of a line in the QMD file, use two spaces or a backslash (\
) to enforce a line break.
To indicate a line break inside a paragraph, you can end
the line with two spaces. Alternatively, you can enforce a line break\ using a backslash.
To prevent Markdown from inserting a line break at a space between words, put a backslash before the non-breaking space and continue with the next word on the same line in the Markdown file (e.g., 100\ km
).
A backslash, followed by a space, in Markdown inserts a non-breaking space in the rendered document.
3.3.1.3 Typesetting Lists
Lists provide a convenient way to organize information. There are three types of lists, each requiring distinct typesetting styles: unordered lists (Section 3.3.1.3.1), ordered lists (Section 3.3.1.3.2), and description lists (Section 3.3.1.3.3). By default, lists should be unordered unless there is a natural sequence for the presented items; in the latter case, an ordered list should be used instead. Description lists are used for presenting a term and its definition, for example, inside a glossary defining key terms within a document.
3.3.1.3.1 Unordered Lists
To produce an unordered list, place either an asterisk (
*
), a hyphen (-
), or a plus sign (+
) as a delimiter before each list item.Leave a blank line before starting a list.
Each item must begin on a new line.
-
Maintain at least one space between the delimiter and the text.
- For nested lists, indent the list item by four spaces.
- As a matter of style, choose different delimiters for the inner and outer lists, for instance:
-
*
for the outer list. -
-
for the sublist. -
+
for the sub-sublist.
-
-
You can insert a paragraph break in a list item.
Simply indent the new paragraph using four spaces.
Afterward, you can continue with the next list item.
Use *
, -
, or +
to delimit items in an unordered list.
Here is the Markdown code for the unordered list above:
* To produce an unordered list, place either an asterisk (`*`), a
`-`), or a plus sign (`+`) as a delimiter before each list
hyphen (
item.* Leave a blank line before starting a list.
* Each item must begin on a new line.
* Maintain at least one space between the delimiter and the text.
- For nested lists, indent the list item by four spaces.
- As a matter of style, choose different delimiters for the inner
and outer lists, for instance: + `*` for the outer list.
+ `-` for the sublist.
+ `+` for the sub-sublist.
* You can insert a paragraph break in a list item.
Simply indent the new paragraph using four spaces.* Afterward, you can continue with the next list item.
3.3.1.3.2 Ordered Lists
- Ordered lists can be initiated by placing one of the following delimiters on a new line. Each delimiter ends with a dot and must be followed by at least one space:
- Arabic numerals (e.g.,
1.
) - Roman numerals (e.g.,
i.
orI.
) - Letters (e.g.,
a.
orA.
)
1.
,i.
,I.
,a.
orA.
. For example, if you want to count from 6, you use6.
as the first delimiter in the list. - Arabic numerals (e.g.,
- Leave a blank line before the first list item.
- It is possible to nest an unordered or ordered list inside an ordered list.
- Simply indent the lists consistently.
- Indent as deeply as needed to keep the delimiters of the inner list flush with the text in the outer list. Take a careful look at the indentation pattern in the source code below.
- Markdown automatically continues the numbering or lettering of the list items. Examine the source code for this list. The number appears as
1
in the source code and 4 in the output. - The aforementioned feature is useful under the following circumstances:
- You have lost track of the count.
- You add more items in the middle of the list, and you do not want to update all following delimiters.
Items in an ordered list can be delimited by Arabic or Roman numerals or letters, each followed by a dot and at least one space.
The following Markdown code renders the ordered list above:
1. Ordered lists can be initiated by placing one of the following
delimiters on a new line. Each delimiter ends with a dot and must be
followed by at least one space: * Arabic numerals (e.g., `1.`)
* Roman numerals (e.g., `i.` or `I.`)
* Letters (e.g., `a.` or `A.`)
At the same level of nestedness, all delimiters must be of the same
type (e.g., all of them may be Arabic numerals). However, you do not`1.`, `i.`, `I.`, `a.` or `A.`. For
need to start counting from `6.` as the first delimiter
example, if you want to count from 6, you use
in the list.2. Leave a blank line before the first list item.
3. It is possible to nest an unordered or ordered list inside an ordered
list.
a. Simply indent the lists consistently.
b. Indent as deeply as needed to keep the delimiters of the inner
list flush with the text in the outer list. Take a careful look
at the indentation pattern in the source code below.1. Markdown automatically continues the numbering or lettering of the
list items. Examine the source code for this list. The number appears`1` in the source code and 4 in the output.
as 10. The aforementioned feature is useful under the following
circumstances:
i. You have lost track of the count.
i. You add more items in the middle of the list, and you do not want to update all following delimiters.
Furthermore, you can
- continue the numbering
of a list after
- an interruption by
- using the
(@)
delimiter.
This example was implemented using the following Markdown code:
Furthermore, you can
(@) continue the numbering
of a list after
(@) an interruption by`(@)` delimiter. (@) using the
3.3.1.3.3 Description Lists
To start a description list, insert a blank line before the term to be described. Start the following line with a colon (:
), trailed by at least one space, before the description. Here is an example of a description list:
- Inner join
- A type of join that returns only the rows that match in both data frames to be joined.
- Left join
- A type of join that returns all rows from the left data frame and the matching rows from the right data frame.
- Right join
- A type of join that returns all rows from the right data frame and the matching rows from the left data frame.
- Full outer join
- A type of join that returns all rows from both data frames.
Here is the Markdown code for the description list above:
Use a colon (:
), followed by at least one space, to delimit the definition of a term in a description list.
To start a description list, insert a blank line before the term to be`:`), trailed by at
described. Start the following line with a colon (
least one space, before the description. Here is an example of a
description list:
Inner join
: A type of join that returns only the rows that match in both data
frames to be joined.
Left join
: A type of join that returns all rows from the left data frame and the
matching rows from the right data frame.
Right join
: A type of join that returns all rows from the right data frame and the
matching rows from the left data frame.
Full outer join : A type of join that returns all rows from both data frames.
3.3.1.4 Block Quotes
You can produce a block quote by placing a greater-than sign (>
) in front of each line of the quote, as the following Markdown code shows:
Use >
followed by a space to mark a block quote.
> I observed that he sat frequently for half and hour on end, with knitted
> brows and an abstracted air, but he swept the matter away with a wave of
> his hand when I mentioned it.
>
> > Data! Data! Data!
>
> he cried impatiently.
>
> > I can't make bricks without clay.
>
> ---Sherlock Holmes, quoted by Dr.\ Watson
---in *The Adventure of the Copper Beeches* by Arthur Conan Doyle (1892)
The rendered output is as follows:
I observed that he sat frequently for half and hour on end, with knitted brows and an abstracted air, but he swept the matter away with a wave of his hand when I mentioned it.
Data! Data! Data!
he cried impatiently.
I can’t make bricks without clay.
—Sherlock Holmes, quoted by Dr. Watson
—in The Adventure of the Copper Beeches by Arthur Conan Doyle (1892)
Please note that three consecutive hyphens (---
), as seen on the last line of the Markdown code, generate an em dash (—) in the output. Similarly, two consecutive hyphens (--
) in Markdown code produce the slightly shorter en dash (–).
Use ---
to generate an em dash (—) in the output and --
to produce an en dash (–).
3.3.2 Formatting Inline Text
The term ‘inline text’ refers to any consecutive part of a text block representing a semantic unit, such as a sequence of words in a paragraph that should be highlighted. This section shows how to typeset inline text using italics and boldface (Section 3.3.2.1), subscripts, superscripts, and footnotes (Section 3.3.2.2), as well as strikethrough text (Section 3.3.2.3). Finally, you will learn how to convert text into hyperlinks (Section 3.3.2.4).
3.3.2.1 Emphasizing Text Using Italics and Boldface
Text to be highlighted in italics can be placed between either a pair of single asterisks or a pair of single underscores.
Here is the text of the previous sentence written in Markdown:
Text between a pair of either single asterisks (*
) or single underscores (_
) is rendered in italics.
Text to be highlighted in italics can be placed between either a pair of *single* asterisks or a pair of _single_ underscores.
Text to be highlighted in boldface can be placed between either a pair of double asterisks or a pair of double underscores.
In Markdown, the previous sentence is written as follows:
Text between a pair of either double asterisks (**
) or double underscores (__
) is rendered in boldface.
Text to be highlighted in boldface can be placed between either a pair of **double** asterisks or a pair of __double__ underscores.
Text to be highlighted in bold italics can be placed between either a pair of triple asterisks or a pair of triple underscores.
The Markdown code for the previous sentence is:
Text between a pair of either triple asterisks (***
) or triple underscores (___
) is rendered in bold italics.
Text to be highlighted in bold italics can be placed between either a pair of ***triple*** asterisks or a pair of ___triple___ underscores.
3.3.2.2 Subscripts, Superscripts, and Footnotes
Markdown can render text as subscripts, superscripts, and footnotes:
- Subscripts:
- Use a pair of tildes. Examples: H2O, log10.
- Superscripts:
- Use a pair of carets. Examples: 1st, km2.
- Footnotes:
- Use Markdown’s footnote2 syntax. Examine the source code to see how the footnote is produced.
Here is the paragraph above written in Markdown:
- Text between a pair of single tildes (
~
) is rendered as subscript. - Text between a pair of single carets (
^
) is rendered as superscript. - Use
[^1]
to anchor a footnote and[^1]:
to define the footnote.
Subscripts:
: Use a pair of tildes. Examples: H~2~O, log~10~.
Superscripts:
: Use a pair of carets. Examples: 1^st^, km^2^.
Footnotes:[^footnote_example] syntax. Examine the source
: Use Markdown's footnote
code to see how the footnote is produced.
[^footnote_example]: Here is a footnote.
3.3.2.3 Strikethrough Text
To strike through text, enclose it in a pair of single double tildes.
The Markdown code for the previous sentence is:
Text between a pair of double tildes (~~
) is struck through in the rendered document.
To strike through text, enclose it in a pair of ~~single~~ double tildes.
3.3.2.4 Hyperlinks
In Markdown, a URL, such as https://google.com/, becomes clickable when enclosed in angle brackets (<...>
). Additionally, you can create a hyperlink with custom text, such as Google Search, by placing the text in square brackets and the URL in parentheses.
Here is the previous paragraph written in Markdown:
Use <https://...>
for clickable URLs and [...](https://...)
for hyperlinks with customized text.
<https://google.com/>, becomes clickable when
In Markdown, a URL, such as `<...>`). Additionally, you can create a
enclosed in angle brackets ([Google Search](https://google.com/), by
hyperlink with custom text, such as placing the text in square brackets and the URL in parentheses.
3.3.3 Computer Code
One of Quarto’s most powerful features is the integration of computer code into a document. There are two distinct ways of printing computer code using plain Markdown. On the one hand, for multiple lines of code intended to be copied and pasted into a text editor, a code block should be used (Section 3.3.3.1). On the other hand, when code is embedded within a text block, it should be presented as inline code (Section 3.3.3.2).
3.3.3.1 Code Blocks
To insert a code block, place the code between a pair of triple backticks (```
), for example:
Text between a pair of triple backticks (```
) is rendered as a code block.
```
s <- sum(1:10)
s
```
The code block above is rendered as follows:
s <- sum(1:10)
s
3.3.3.1.1 Syntax Highlighting
To enable syntax highlighting, specify the programming language after the initial set of triple backticks, for example:
Use ```r
, ```python
, etc., to enable syntax highlighting.
```r
<- sum(1:10)
s ```
In the rendered code block, the function name and the argument are highlighted in distinct colors:
s <- sum(1:10)
Please be aware that the code blocks above are solely printed and not executed. Consequently, even after rendering these code blocks, there is no variable s
available for evaluation by other code chunks in the QMD file. You will learn how to write executable code chunks in Section 3.4.
3.3.3.1.2 Code Blocks within List Items
You can embed a code block within a list item, as the following example illustrates:
You can add the ten smallest positive integers with the following four R
expressions:
1. *Bad:* Hard-code all ten integers:
```r
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
```
2. *Better:* Use a `for`-loop:
```r
<- 0
s for (i in 1:10) {
<- s + i
s
}
s```
3. *Even better:* Use R's built-in vectorized `sum()` function:
```r
sum(1:10)
```
4. *Best:* Use the formula for the sum of an arithmetic series:
```r
10 * (10 + 1) / 2
```
Ensure proper indentation of a code block when it is within a list item.
The output generated by this Quarto Markdown code is displayed below. Please observe that the code blocks are left-aligned with the text inside the list items:
You can add the ten smallest positive integers with the following four R expressions:
3.3.3.2 Inline Code
Computer code is conventionally displayed in monospaced font. To include monospaced computer code as part of a sentence, enclose the code in a pair of backticks (e.g., sum(1:10)
).
Here is the previous sentence written in Markdown:
Text between a pair of single backticks (`
) is rendered as inline code.
To include monospaced computer code as part of a sentence, enclose the`sum(1:10)`). code in a pair of backticks (e.g.,
In this example, the code is printed but not executed. If you want to execute inline R code using the Knitr engine and display the result in the text, you should place an r
after the first backtick. For instance, `r sum(1:10)`
prints the number 55. If you use Jupyter instead of Knitr, you can run inline code in Python or Julia, as detailed on the Quarto website.
3.3.4 Backslash Escapes
As demonstrated in the preceding sections, Markdown employs special characters for text formatting, such as hash symbols (#
) for section headings or backticks (`) for inline code. Occasionally, it is necessary to include these special characters verbatim in the text. In such cases, you can use a backslash (\
) to escape the special character, for example:
\#\#\# These are three hash symbols instead of a third-level heading.
This Markdown code produces the following output:
### These are three hash symbols instead of a third-level heading.
Use a backslash (\
) to escape special Markdown characters.
The backslash (\
) itself can be escaped by another backslash, as shown in the following example:
`\\`) itself can be escaped by another backslash. The backslash (
3.3.5 Raw HTML
While Markdown provides most of the formatting options used in practice, occasionally you may encounter typesetting challenges not covered by Markdown itself. One example is the lack of Markdown-native syntax for non-breaking hyphens,3 required in words such as “24‑inch monitor.”
In such cases where no native Markdown solution exists, raw HTML can be inserted as part of Markdown text. For instance, a non-breaking hyphen can be implemented using the HTML character entity ‑
:
You can use raw HTML to insert special characters not provided by Markdown.
‑inch monitor 24
A comprehensive list of HTML character entities is available from the Web Hypertext Application Technology Working Group (2024).
An important use case for raw HTML in Markdown is the inclusion of comments in the Markdown code. For example, when a Markdown file fails to render due to a syntax error, commenting out parts of the Markdown text can help pinpoint the faulty section. HTML uses the following syntax for comments, also recommended for Quarto Markdown by the Quarto GitHub repository:
<!-- This is a comment. -->
<!-- Comments can extend
over multiple lines. -->
It is also possible to insert more complex HTML code, such as tables, images, or videos, into a Markdown document. However, the unnecessary use of raw HTML in Markdown is discouraged because it can make the document harder to maintain and less likely to render correctly in non-HTML formats, such as PDF.
3.3.6 Section Summary: Marked-Up Text
Markdown is a simple markup language enabling the creation of formatted text documents. Table 3.1 summarizes the Markdown skills acquired in this section. For more comprehensive information on Markdown, refer to the Markdown Guide.
Markdown | Rendered |
---|---|
# , ## , … ######
|
Top-level, 2nd-level, …, 6th-level heading |
Blank line | Paragraph break |
Two spaces or one backslash (\ ) at the end of a line |
Line break |
\ followed by space not at the end of a line |
Non-breaking space |
* One item * Another item - One subitem - Another subitem + One sub-subitem + Another sub-subitem
|
Unordered list |
1. First item 2. Second item i. i-th item ii. ii-th item a. a-th item b. b-th item
|
Ordered list |
Term 1 : Description 1 Term 2 : Description 2
|
Description list |
*Italics* or _Italics_
|
Italics |
**Bold** or __Bold__
|
Bold |
***Bold italics*** or ___Bold italics___
|
Bold italics |
Sub~script~ |
Subscript |
Super^script^ |
Superscript |
Anchor[^footnote] [^footnote]: Footnote text
|
Footnote |
~~Strikethrough~~ |
|
<https://google.com/> |
https://google.com/ |
[Google Search](https://google.com/) |
Google Search |
```r sum(1:10) ```
|
Code block, not executed |
`sum(1:10)` |
Inline code, not executed |
`r sum(1:10)` |
Inline code, executed |
\\ , \` , \* , \_ , \{ , \} , \[ , \] ,\( , \) , \# , \+ , \- , \. , and \!
|
Backslash escape for verbatim output of special characters |
&#8209; |
Raw HTML (e.g., non-breaking hyphen) |
<!-- This is a comment. --> |
Comment |
3.4 Code Chunks
Code chunks are a powerful feature of Quarto, enabling the inclusion and rendering of code in various ways. This section will guide you through the process of creating code chunks (Section 3.4.1) before you will learn how to leverage RStudio to preview their output (Section 3.4.2). Additionally, by the end of this section, you will be able to label code chunks for reuse in other parts of the document (Section 3.4.3), specify execution options (Section 3.4.4), and embed graphics from external files (Section 3.4.5).
3.4.1 Creating New Code Chunks
Going beyond code blocks written in plain Markdown, as explored in Section 3.3.3.1, Quarto introduces code chunks which, unlike Markdown’s mere display of code, enable code execution and embedding of its output directly in the rendered document. Similar to plain-Markdown code blocks, the start and end of an R code chunk are marked by three backticks. The opening triplet of backticks is immediately followed by {r}
, for example:
For R code chunks, use the following syntax:
```{r}
```
```{r}
sum(1:10)
```
[1] 55
You can expedite the creation of boilerplate code for an R code chunk by clicking on the “c” button at the top of the editor pane (Figure 3.6). Alternatively, you can use the keyboard shortcut Ctrl-Alt-ICtrl-Alt-I (Windows and Linux) or Command-Option-ICommand-Option-I (Mac).
3.4.2 Using RStudio to Preview the Output from Code Chunks
RStudio offers a convenient way to preview the output of code chunks directly within the editor pane. To the right of each code chunk, there is a green arrow pointing to the right, highlighted in Figure 3.7. Clicking on this arrow will execute the current code chunk, and its output will be displayed below. Please note that modifications of the code chunk will not automatically update the output. Instead, you will need to click on the green arrow again to view the updated results.
Prior to updating, it might be necessary to run all preceding code chunks to ensure that the latest input variables are available. To execute all code chunks above the current one, click on the grey downward arrow, located immediately to the left of the green arrow.
Clicking on the green arrow in the top right corner of a code chunk will execute it and display its output in the editor pane.
3.4.3 Chunk Labels
Chunk labels enable referring to code chunks with user-defined names. It is advisable to label every code chunk because it simplifies debugging and facilitates automatic code reuse.
For instance, consider the following code chunk, labelled purposefully-wrong
. Please note that it intentionally lacks a closing parenthesis for demonstration purposes:
Use #| label: ...
to label a code chunk.
```{r}
#| label: purposefully-wrong
sum(1:10
```
Upon rendering the code, Quarto will display an error message, which includes the label of the code chunk responsible for the error. This feature simplifies locating the faulty code chunk:
Quitting from lines 2-5 [purposefully-wrong] (code_chunks.qmd)
Labels also facilitate reusing code from one chunk in another, minimizing the need for code duplication. For example, let us fix the previous code chunk and label it as sum-from-1-to-10
:
```{r}
#| label: sum-from-1-to-10
sum(1:10)
```
[1] 55
The following code chunk reuses the previous one because they share the same label:
```{r}
#| label: sum-from-1-to-10
```
The latest code chunk will be rendered as follows:
sum(1:10)
[1] 55
Please note that Quarto will throw an error message if you attempt to modify the code in a reused chunk:
```{r}
#| label: sum-from-1-to-10
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
```
Error in parse_block(g[-1], g[1], params.src, markdown_mode) :
Duplicate chunk label 'sum-from-1-to-10', which has been used for the chunk:
sum(1:10)
3.4.4 Execution Options
Execution options control the behavior of code chunks, for example, determining whether the code should be evaluated or displayed in the rendered document. These options are specified immediately after the label, with each option preceded by #|
and a space. For instance, the following code chunk applies the eval: false
execution option, preventing code evaluation during the rendering process:
```{r}
#| label: sum-from-1-to-10
#| eval: false
sum(1:10)
```
This section will introduce some of the most frequently used execution options: eval
(Section 3.4.4.1), echo
(Section 3.4.4.2), error
, message
, and warning
(Section 3.4.4.3), as well as include
(Section 3.4.4.4). Execution options can be set either for each code chunk individually or, as shown in Section 3.4.4.5, for all code chunks in the document.
3.4.4.1 Evaluation
In most Quarto output formats, code chunks are evaluated by default, and the results are rendered in the document. However, you can choose to prevent a code chunk from being evaluated by setting the eval: false
execution option. This option is useful, for example, if you want to demonstrate a deliberately wrong code chunk:
Use #| eval: false
to prevent a code chunk from being evaluated.
```{r}
#| label: purposefully-wrong-again
#| eval: false
"Hello, world!" + 1
```
Without setting eval: false
, this code chunk would have caused an error, and the rendering process would have been aborted:
Error in "Hello, world!" + 1: non-numeric argument to binary operator
3.4.4.2 Echos
Code chunks are rendered as code blocks in the output document by default. However, it is possible to hide the code chunk by setting the echo: false
execution option, which is useful when you want to focus the reader’s attention on the output rather than the source code. The following example can be used to display the numbers from 1 to 10 without showing the code 1:10
that generates them:
Use #| echo: false
to prevent a code chunk from being displayed in the rendered document.
```{r}
#| label: one-to-ten
#| echo: false
1:10
```
[1] 1 2 3 4 5 6 7 8 9 10
Besides false
and the true
default value, the echo
option accepts the value fenced
, which displays not only the code but also the entire code cell syntax in the rendered document. For example, consider the following code chunk, where the echo
option is set to fenced
:
Use #| echo: fenced
to display the entire code cell syntax in the rendered document.
```{r}
#| label: fence-demo
#| echo: fenced
#| eval: false
1 + 1
```
This code chunk will be rendered as shown below. Please note that, while the echo
option itself is not displayed, all other features of the code cell will be visible, such as the label, any other execution options, and the triple tick marks (```):
```{r}
#| label: fence-demo
#| eval: false
1 + 1
```
3.4.4.3 Errors, Messages, and Warnings
By default, the rendering process is aborted when a code chunk generates an error. However, it is sometimes desirable to show the error message in the rendered document and continue rendering. In such cases, the user should activate the error: true
execution option. For example, the following code chunk generates and displays the error, allowing the rendering process to continue:
Use #| error: true
to display any potential error message in the rendered document and continue rendering.
```{r}
#| label: purposefully-wrong-yet-again
#| error: true
"Hello, world!" + 1
```
Error in "Hello, world!" + 1: non-numeric argument to binary operator
While errors indicate wrong usage of code, non-error messages communicate information that may be helpful when analyzing the code without implying any serious problem. Messages may, for instance, simply reveal the progress of a long-running calculation. For example, the following code generates and displays a message on every iteration of a for
loop:
```{r}
#| label: message-demo
max_iter <- 3
for (i in 1:max_iter) {
message("Performing iteration ", i, " out of ", max_iter, ".")
}
```
Often, such messages are irrelevant to the reader and should not be included in the rendered document. In such cases, the user should opt for message: false
:
Use #| message: false
to prevent any potential code messages from being displayed in the rendered document.
```{r}
#| label: message-demo
#| message: false
max_iter <- 3
for (i in 1:max_iter) {
message("Performing iteration ", i, " out of ", max_iter, ".")
}
```
Warnings occupy the middle ground between errors and non-error messages. Like non-error messages, warnings do not cause the rendering process to abort. However, like errors, warnings indicate a problem with the code. For instance, the following code chunk generates a warning because the square root of a negative number is not defined. By the way, NaN
in the output stands for “Not a Number”:
In principle, it is possible to suppress warnings using the warning: false
execution option. However, I generally advise against suppressing warnings. Instead, it is preferable to fix the code so that it does not generate warnings in the first place. For instance, if a mathematical operation produces NaN
, the user should investigate the cause, which may reveal a more fundamental problem with the underlying data.
The warning: false
execution option suppresses warnings, but use it with caution.
3.4.4.4 Inclusions
Sometimes, it is useful to execute a code chunk without displaying the code, the output, or any messages or warnings. An example is the initial code chunk in a QMD file, commonly labelled as setup
, which performs bookkeeping tasks of little interest to the reader, such as loading packages, establishing database connections, or seeding a random number generator. In such cases, the user should choose the include: false
execution option. For instance, the following code chunk, which loads the tidyverse suite of R packages, will be executed but not included in the rendered document:
Use #| include: false
to execute a code chunk without displaying the code, its output, or any messages or warnings.
```{r}
#| label: setup
#| include: false
library(tidyverse)
```
3.4.4.5 Setting Document-Wide Execution Options
In addition to configuring execution options on a per-chunk basis, they can be set for the entire document using the execute
key in the YAML header. For instance, the following YAML code sets the echo
option to fenced
and the error
option to true
for all code chunks in the document:
---
title: "Document-Wide Execution Options"
execute:
echo: fenced
error: true
---
Use the execute
key in the YAML header to define document-wide execution options.
Please note that explicit chunk-level execution options will still override any document-wide settings.
3.4.5 Including Graphics from External Files
Quarto Markdown allows embedding images from external files in standard graphics formats, such as the following PNG, which you can download from the book website, using two different methods. First, you can include an image file using pure Markdown syntax, following this pattern:
{width=65%}
The rendered output of this Markdown code is displayed below. Please note that the width specified inside the curly braces is defined as the percentage of the text width:
This pure-Markdown approach is appropriate if the text does not contain a reference to an identifier for the figure (e.g., “Figure 1”). While it is possible to hard-code a figure number in the Markdown caption, this approach is not recommended. If, for instance, you hard-code the caption as “Figure 1,” that figure number remains fixed even if you later insert another image earlier in the document. A better option is to use the include_graphics()
function in R’s knitr package. It allows users to specify the figure caption through the fig-cap
execution option; the correct figure number is then determined during rendering. Please note that the label of code chunks containing numbered figure captions needs to start with fig-
, as shown here:
Use the include_graphics()
function in R’s knitr package to embed images from external files.
```{r}
#| label: fig-ggplot2-cartoon
#| fig-cap: "Image by Aye Chan Phyu Sin."
#| out-width: 65%
knitr::include_graphics("url_or_local_path/cartoon.png")
```

Thanks to the chunk label, you can now refer to the figure as @fig-ggplot2-cartoon
, which is rendered as “Figure 3.8.”
3.4.6 Section Summary: Code Chunks
This section has introduced code chunks and explained various execution options for them. These options determine, for example, whether the source code is displayed in the rendered document, whether the code is executed, and whether error messages are displayed. Table 3.2 summarizes the most important execution options for code chunks.
Option | Values | Description |
---|---|---|
eval |
true , false
|
Execute the code chunk? |
echo |
true , false , fenced
|
Display the source code in the rendered document? |
error |
true , false
|
Display error messages in the rendered document? |
message |
true , false
|
Display messages in the rendered document? |
warning |
true , false
|
Display warnings in the rendered document? |
include |
true , false
|
Include the code in the rendered document? |
fig-cap |
String | Caption for the figure. |
out-width |
Percentage (e.g., 60% ) |
Figure width relative to the text width of the rendered document. |
For more execution options, consult the Quarto documentation. You will encounter additional execution options for rendering figures in Section 6.3.
3.5 Conclusion
In this chapter, you have acquired essential skills for communicating the work of a data scientist using Quarto. You now know how to create and structure a QMD file, mark up text, and include code chunks. Quarto will be your faithful companion throughout the remainder of this book.
While Quarto can execute code in various programming languages, its support for R is especially strong. Additionally, R provides excellent tools for data analysis and visualization. Therefore, the following chapter will focus on R, introducing you to its fundamental concepts and syntax.
The visual editor presents a “What You See Is What You Mean” interface, mainly beneficial for beginners. However, I recommend using the source editor instead of the visual editor because it will reinforce your learning of Quarto syntax. Additionally, typing the source code is generally faster than navigating through the visual editor’s menu options.↩︎
Here is a footnote.↩︎
The lack of Markdown-native syntax for non-breaking hyphens has been discussed on StackOverflow.↩︎