28  Quarto Advanced

28.1 Callout Blocks

Callouts are an excellent way to draw extra attention to certain concepts, or to more clearly indicate that certain content is supplemental or applicable to only some scenarios.

28.1.1 Callout Types

There are five different types of callouts available.

  • note
  • warning
  • important
  • tip
  • caution

The color and icon will be different depending upon the type that you select. Here are what the various types look like in HTML output:

Note

Note that there are five types of callouts, including: note, tip, warning, caution, and important.

Warning

Callouts provide a simple way to attract attention, for example, to this warning.

Important

Danger, callouts will really improve your writing.

Tip with Title

This is an example of a callout with a title.

This is an example of a “collapsed” caution callout that can be expanded by the user. You can use collapse="true" to collapse it by default or collapse="false" to make a collapsible callout that is expanded by default.

28.1.2 Markdown Syntax

Create callouts in markdown using the following syntax (note that the first markdown heading used within the callout is used as the callout heading):

::: {.callout-note}
Note that there are five types of callouts, including:
`note`, `warning`, `important`, `tip`, and `caution`.
:::

::: {.callout-tip}
## Tip with Title

This is an example of a callout with a title.
:::

::: {.callout-caution collapse="true"}
## Expand To Learn About Collapse

This is an example of a 'folded' caution callout that can be expanded by the user. You can use `collapse="true"` to collapse it by default or `collapse="false"` to make a collapsible callout that is expanded by default.
:::

Note that above callout titles are defined by using a heading at the top of the callout. If you prefer, you can also specify the title using the title attribute. For example:

::: {.callout-tip title="Tip with Title"}
This is a callout with a title.
:::

Exercise A

Q1
  1. Within AQuartoExample.qmd, add a section called “Callout Blocks”.
  2. Insert a folded warning callout block that can be expanded by the user. Use a title of “Expand to See Warning” and include the text “This is a foldable warning callout block.”.

28.2 Figures

The figures in a Quarto document can be embedded (e.g., a PNG or JPEG file) or generated as a result of a code chunk. Below is the syntax for inserting a figure file which is in your current working directory.

![optional caption text](figure.png){fig-alt="optional alt text"}

For example:

![Quarto Logo](imgs/quartologo.png){fig-alt="insert quarto logo"}

results in the following output:

insert quarto logo

Quarto Logo
Tip

Note that when specifying the options in {}. Do NOT use spaces before and after the =.

Alternatively, to embed an image from an external file, you can use the Insert menu in the Visual Editor in RStudio and select Figure / Image. This will pop open a menu where you can browse to the image you want to insert as well as add alternative text or caption to it and adjust its size. In the visual editor you can also simply paste an image from your clipboard into your document and RStudio will place a copy of that image in your project folder.

If you include a code chunk that generates a figure (e.g., includes a ggplot() call), the resulting figure will be automatically included in your Quarto document.

28.2.1 Figure Sizing

28.2.1.1 External file

By default figures are displayed using their actual size (subject to the width constraints imposed by the page they are rendered within). You can change the display size by adding the width and height attributes to the figure. For example

![Quarto Logo](imgs/quartologo.png){width=300}

Quarto Logo

Note that if only width is specified then height is calculated automatically. If you need to modify the default behavior just add an explicit height attribute.

The default units for width and height are pixels. You can also specify sizes using a percentage or a conventional measurement like inches or millimeters. For example:

![](imgs/quartologo.png){width=80%}

![](imgs/quartologo.png){width=2in}

If you have several figures that appear as a group, you can create a figure division to enclose them. For example:

::: {#fig-logos layout-ncol=2}

![Quarto](quartologo.png){#fig-Qurto}

![R Markdown](rmarkdownlogo.png){#fig-RMarkdown}

Reporting in R
:::
(a) Quarto
(b) R Markdown
Figure 28.1: Reporting in R
Tip

Note that the empty lines between the figures (and between the last figure and the caption) are required (it is what indicates that these images belong to their own paragraphs rather than being multiple images within the same paragraph).

Note also that we also used a layout-ncol attribute to specify a two-column layout.

Exercise B

Q1
  1. Create a new section called “Figures” in AQuartoExample.qmd.
  2. Insert the following image AUlogo.png which can be downloaded from Canvas.
    • The image has a Caption “Arcadia Logo”
    • Add fig-alt="Insert Arcadia Logo" as the alternative text for the image.
    • Set the width by 20%.
    • Your output should look like the following.

Insert Arcadia Logo

Arcadia Logo

28.2.1.2 Graph generated by R code

Getting the right size and shape for a graph created by R in Quarto can be more challenging. There are five main chunk options that control figure sizing: fig-width, fig-height, fig-asp, out-width and out-height. Image sizing is challenging because there are two sizes (the size of the figure created by R and the size at which it is inserted in the output document), and multiple ways of specifying the size (i.e. height, width, and aspect ratio: pick two of three).

We recommend three of the five options:

  • Plots tend to be more aesthetically pleasing if they have consistent width. To enforce this, set fig-width: 6 (6”) and fig-asp: 0.618 (the golden ratio) in the defaults. Then in individual chunks, only adjust fig-asp.

  • Control the output size with out-width and set it to a percentage of the body width of the output document. We suggest to out-width: "70%" and fig-align: center. That gives plots room to breathe, without taking up too much space.

  • To put multiple plots in a single row, set the layout-ncol to 2 for two plots, 3 for three plots, etc. This effectively sets out-width to “50%” for each of your plots if layout-ncol is 2, “33%” if layout-ncol is 3, etc. Depending on what you are trying to illustrate (e.g., show data or show plot variations), you might also tweak fig-width, as discussed below.

If you find that you are having to squint to read the text in your plot, you need to tweak fig-width. If fig-width is larger than the size the figure is rendered in the final doc, the text will be too small; if fig-width is smaller, the text will be too big. You will often need to do a little experimentation to figure out the right ratio between the fig-width and the eventual width in your document. To illustrate the principle, the following three plots have fig-width of 4, 6, and 8 respectively:

If you want to make sure the font size is consistent across all your figures, whenever you set out-width, you will also need to adjust fig-width to maintain the same ratio with your default out-width. For example, if your default fig-width is 6 and out-width is “70%”, when you set out-width: “50%” you will need to set fig-width to 4.3 (6 * 0.5 / 0.7).

Figure sizing and scaling is an art and science and getting things right can require an iterative trial-and-error approach. You can learn more about figure sizing in the taking control of plot scaling blog post.

Exercise C

Q1

Work with the plot generated in AQuartoExample.qmd. Experiment with the fig-width, fig-asp, out-width, and fig-align options to understand how each affects the appearance of the plot..

28.3 Tables

Similar to figures, you can include two types of tables in a Quarto document. They can be markdown tables that you create directly in your Quarto document (using the Insert Table menu) or they can be tables generated as a result of a code chunk.

28.3.1 Table Created by Markdown Syntax

A table can be created by the following syntax.

| Right | Left | Default | Center |
|------:|:-----|---------|:------:|
|   12  |  12  |    12   |    12  |
|  123  |  123 |   123   |   123  |
|    1  |    1 |     1   |     1  |

As a result, we will get:

Right Left Default Center
12 12 12 12
123 123 123 123
1 1 1 1

Exercise D

Q1
  1. Add a new section in AQuartoExample.qmd called “Tables”.
  2. Insert the following table using Markdown syntax to your “Tables” section.
Customer ID Customer Name Transaction Amount Payment Method
1 John 35 Cash
2 David 47 Debit
3 Amy 58 Credit

28.3.2 Table Created in Code Chunks

In this section we will focus on tables generated via computation.

By default, Quarto prints data frames and matrices as you would see them in the console:

head(mtcars)

If you prefer that data be displayed with additional formatting you can use the knitr::kable() function. Take a look at the output generated from the code below.

knitr::kable(head(mtcars))
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1

Refer to the documentation for ?knitr::kable to see the other ways in which you can customize the table. For even deeper customization, consider the gt, huxtable, reactable, kableExtra, xtable, stargazer, pander, tables, and ascii packages. Each provides a set of tools for returning formatted tables from R code.

Exercise E

Q1

Under the “Tables” section you created in Exercise D in AQuartoExample.qmd, insert a code chunk, and add a table with knitr::kable() that shows the first 5 rows of the stackloss data frame and include a caption “Table 1: Stack Loss” to the table.

28.4 YAML Header

You can control many other “whole document” settings by tweaking the parameters of the YAML header. You might wonder what YAML stands for: it is “YAML Ain’t Markup Language”, which is designed for representing hierarchical data in a way that is easy for humans to read and write. Quarto uses it to control many details of the output. Here we will discuss self-contained documents and document parameters.

28.4.1 Self-contained

HTML documents typically have a number of external dependencies (e.g., images, CSS style sheets, JavaScript, etc.) and, by default, Quarto places these dependencies in a _files folder in the same directory as your .qmd file. If you publish the HTML file on a hosting platform (e.g., QuartoPub, https://quartopub.com/), the dependencies in this directory are published with your document and hence are available in the published report. However, if you want to email the report to a colleague, you might prefer to have a single, self-contained, HTML document that embeds all of its dependencies. You can do this by specifying the embed-resources option:

format:
  html:
    embed-resources: true

The resulting file will be self-contained, such that it will need no external files and no internet access to be displayed properly by a browser.

28.4.2 Parameters

Quarto documents can include one or more parameters whose values can be set when you render the report. Parameters are useful when you want to re-render the same report with distinct values for various key inputs. For example, you might be producing sales reports per branch, exam results by student, or demographic summaries by country. To declare one or more parameters, use the params field.

This example uses a my_class parameter to determine which class of cars to display:

---
format: html
params:
  my_class: "suv"
---

```{r}
#| label: setup
#| include: false

library(tidyverse)

class <- mpg |> filter(class == params$my_class)
```

# Fuel economy for `r params$my_class`s

```{r}
#| message: false

ggplot(class, aes(x = displ, y = hwy)) + 
  geom_point() + 
  geom_smooth(se = FALSE)
```

As you can see, parameters are available within the code chunks as a read-only list named params.

You can write atomic vectors directly into the YAML header. You can also run arbitrary R expressions by prefacing the parameter value with !expr. This is a good way to specify date/time parameters.

---
format: html
params:
  start: !expr as.Date("2010-01-01")
---

```{r}
#| label: setup
#| include: false

library(tidyverse)

economics_subset <- economics |>
  filter(date >= params$start)
```

```{r}
#| message: false

economics_subset |>
  ggplot(aes(x = date, y = unemploy / pop)) +
  geom_line()
```

Exercise F

Q1
  1. In the YAML header of the AQuartoExample.qmd document, set a filtering threshold for Air.Flow at 60. This will enable you to render a report only for experiments with the flow of cooling air below 60.

  2. Render the report incorporating all modifications from previous exercises, and review the changes in the output HTML file compared to the original.

28.5 Troubleshooting and More

28.5.1 Troubleshooting

Troubleshooting Quarto documents can be challenging because you are no longer in an interactive R environment, and you will need to learn some new tricks. Additionally, the error could be due to issues with the Quarto document itself or due to the R code in the Quarto document.

One common error in documents with code chunks is duplicated chunk labels, which are especially pervasive if your workflow involves copying and pasting code chunks. To address this issue, all you need to do is to change one of your duplicated labels.

If the errors are due to the R code in the document, the first thing you should always try is to recreate the problem in an interactive session. Restart R, then “Run all chunks”, either from the Code menu, under Run region or with the keyboard shortcut Cmd + Options + R (Mac) or Ctrl + Alt + R (Windows). If you are lucky, that will recreate the problem, and you can figure out what is going on interactively.

If that does not help, there must be something different between your interactive environment and the Quarto environment. You are going to need to systematically explore the options. The most common difference is the working directory: the working directory of a Quarto is the directory in which it lives. Check the working directory is what you expect by including getwd() in a chunk.

Next, brainstorm all the things that might cause the bug. You will need to systematically check that they are the same in your R session and your Quarto session. The easiest way to do that is to set error: true on the chunk causing the problem, then use print() and str() to check that settings are as you expect.

28.5.2 More to Explore

In this chapter we introduced you to Quarto for authoring and publishing reproducible computational documents that include your code and your prose in one place. You have learned about writing Quarto documents in RStudio with the visual or the source editor, how code chunks work and how to customize options for them, and how to include figures and tables in your Quarto documents. Additionally, you have learned about adjusting YAML header options for creating self-contained or parametrized documents. We have also given you some troubleshooting tips.

While this introduction should be sufficient to get you started with Quarto, there is still a lot more to learn. Quarto is still relatively young, and is still growing rapidly. The best place to stay on top of innovations is the official Quarto website: https://quarto.org.

There is another important topic that we have not covered here: collaboration. Collaboration is a vital part of modern data science, and you can make your life much easier by using version control tools, like Git and GitHub. You are recommended to read “Happy Git with R”, a user friendly introduction to Git and GitHub from R users, by Jenny Bryan. The book is freely available online: https://happygitwithr.com.