Welcome to Quarto

Workshop: Quarto for R & RStudio
posit::conf 2023

Introductions

Take ~2 minutes to introduce yourself to your neighbors.


Please share …

  1. Your name
  2. Where you’re from
  3. What you work on in 3 words or fewer
  4. Name one thing you’ve made that you’re proud of

About the Workshop




Workshop materials are at:

pos.it/quarto-r-conf23



Goals for the Workshop

  1. Everyone leaves with a report and presentation.

  2. Learn from one another.

  3. Build an understanding of the big picture.

From Magic to Magical Machines

Two fuzzy round monsters dressed as wizards, working together to brew different things together from a pantry (code, text, figures, etc.) in a cauldron labeled “R Markdown”. The monster wizard at the cauldron is reading a recipe that includes steps “1. Add text. 2. Add code. 3. Knit. 4. (magic) 5. Celebrate perceived wizardry.” The R Markdown potion then travels through a tube, and is converted to markdown by a monster on a broom with a magic wand, and eventually converted to an output by pandoc. Stylized text (in a font similar to Harry Potter) reads “R Markdown. Text. Code. Output. Get it together, people.”

Artwork by Allison Horst

A technical sketch of a lightbulb

Workshop Schedule


Introduction to Quarto

Discussions: discord

Ask questions at #introduction-to-quarto-with-r-and-rstudio.

Screenshot of the discord server app that serves as the forum for the workshop.

Flow of the Workshop

Stickies

Picture of a laptop with a red sticky note stuck to the top.

During an activity, place a blue sticky on your laptop if you’re good to go and a red sticky if you want help.

Practicalities

  • WiFi:
    • Network: Posit Conf 2023
    • Password: conf2023
  • There are gender-neutral bathrooms located are among the Grand Suite Bathrooms.
  • There are two meditation/prayer rooms: Grand Suite 2A and Grand Suite 2B. Open Sunday - Tuesday 7:30 a.m. - 7:00 p.m., Wednesday 8:00 a.m. - 6:00 p.m.
  • The lactation room is located in Grand Suite 1. Open Sunday - Tuesday 7:30 a.m. - 7:00 p.m., Wednesday 8:00 a.m. - 6:00 p.m.
  • Participants who do not wish to be photographed have red lanyards; please note everyone’s lanyard colors before taking a photo and respect their choices.
  • The Code of Conduct and COVID policies can be found at https://posit.co/code-of-conduct/. Please review them carefully. You can report Code of Conduct violations in person, by email, or by phone. Please see the policy linked above for contact information.

Hello Quarto!

Sit back and enjoy the tour!

Join me in Posit Cloud!

Your Turn

Open hello-penguins.qmd in RStudio and…

  1. Render the document.
  2. Replace the name with your own and re-render.
  3. Inspect the components of the document and modify one or two more and re-render. Consider changing the options at the top, the text, or the code.
  4. Look carefully through the source of hello-penguins.qmd. What do you notice that’s different from what it would look like in an Rmd document? Work with your neighbor to see if you can find the differences (there are at least 3).
10:00

What can you do with Quarto?

Articles

Presentations

Websites

Books

Quarto and R Markdown

Quarto and R Markdown, a history . . .

  • 1984 Literate Programming proposed to combine text with code
  • 2002 Sweave weaves together S/R and \(\TeX\)
  • 2006 pandoc converts between different document formats
  • 2012 knitr a next gen Sweave for R and Markdown
  • 2014 knitr::pandoc added to leverage pandoc flexible outputs
  • 2015 pandoc functionality moved into new rmarkdown
  • 2018 R Markdown: A definite guide
  • 2020 R Markdown Cookbook

. . . throughout, an ecosystem of R packages develops . . . (bookdown, blogdown, distill, etc.)

How is Quarto Different than R Markdown?

  1. Quarto is compute-agnostic. R Markdown requires R.

  2. The ecosystem of R packages is replaced by a single framework.

What can you do with R Markdown that you can’t with Quarto?

  • Access tools built around R Markdown (e.g. workflowr, papaja) that haven’t yet been implemented in Quarto.

Heavy users of such tools may want to stick with R Markdown.

What can you do with Quarto that you can’t with R Markdown?

  • Easier to organize appearance across documents
  • Features (e.g. figures, tables) have better cross-format support
  • Better cross referencing
  • Up-to-date revealjs slides
  • Easier to customize websites and books with projects
  • Convince your Python-user colleagues to use it

Note: You can render existing R Markdown documents with Quarto and/or rename them to .qmd files to turn them into Quarto documents.

Rendering in Quarto






Inputs






Outputs

Quarto Render

Render input file to various document formats.


Input

  • *.qmd
  • *.ipynb
  • *.md
  • *.Rmd

Format

  • html
  • pdf
  • revealjs
  • docx
  • ppt
  • and many more!


Three ways to render

  1. Quarto is integrated into RStudio

    Click small icon of render arrow in Editor pane of RStudio.

  1. Quarto is an R package

    Run in R:

    quarto::quarto_render(input = ___, output_format = ___)
  1. Quarto has a command line interface (CLI)

    Run at the terminal:

    quarto render <input> --to <format>

Element expression depends on format

Emphasis

HTML

A <em>spatial logical toy</em>

LATEX

A \emph{spatial logical toy}


Image

HTML

<img src="images/med-rubiks-cube.png" class="img-fluid">

LATEX

\includegraphics{images/med-rubiks-cube.png}

Your Turn

  1. Render 2-formats.qmd to html and view the html file in an editor. How is the list expressed in html? (you can click on it in the Files pane)

  2. Render 2-formats.qmd to latex and view the latex file in an editor. How is the list expressed in latex?

  3. Change the extension of 2-formats.qmd to be .md and .Rmd and re-render. Does the output differ?

  4. Try rendering the file to a pdf format but this time using the CLI (command line interval) in the Terminal tab.

    quarto render <input> --to <format>
07:00

Try Pandoc!

A quick way to find out how Pandoc will convert: https://pandoc.org/try/.

Anatomy of a Document

  1. Metadata
  2. Text
  3. Code Cells

Metadata

Metadata: YAML

“Yet Another Markup Language” or “YAML Ain’t Markup Language” is used to provide document level metadata …

… in key-value pairs,

… that can nest,

… are fussy about indentation,

… and are kept between ---.


---
format: 
  html:
    toc: true
    code-fold: true
---

Which of the following are valid ways to include metadata?

A

---
title: US Patent: A Spatial Toy
author: Erno Rubik
format: html
---

My idea is to build a cube...

C

---
format: html
---

My idea is to build a cube...

---
title: A Spatial Toy
author: Erno Rubik
---

C

My idea is to build a cube...

… then at the command line, run:

quarto render patent.qmd --to html -M title:patent

D

---
title: "US Patent: A Spatial Toy"
author: "Erno Rubik"
format: "html"
---

My idea is to build a cube...

Metadata: YAML Syntax Rules

---
title: "US Patent: A Toy"
author:
  - Erno Rubrik
  - Albert Einstein
format:
  html:
    toc: true
    abstract: |
      This is the abstract.

      It has two paragraphs.
---
  • Set a single value with

    key: value
  • Set a list of values either:

    key: [val1, val2]
    key:
      - val1
      - val2
  • Quote values that contain :

  • Indent 2 spaces to nest

  • Multi-line strings follow |

  • Multiple YAML blocks will be merged

Metadata: Fussing with YAML

Invalid

---
format:html
---


---
format:
html
---


---
format: 
  html:
---

Valid

format: html


format:
  html


format: 
  html:
    toc: true

Quarto linting

Lint, or a linter, is a static code analysis tool used to flag programming errors, bugs, stylistic errors and suspicious constructs.


Quarto YAML Intelligence

RStudio + VSCode provide rich tab-completion - start a word and tab to complete, or Ctrl + space to see all available options.


Your Turn

  • Open hello-penguins.qmd in RStudio.
  • Try Ctrl + space to see the available YAML options.
  • Try out the tab-completion of any options that sound interesting.
  • Bring back your two favorite to share in chat when we return from breakout rooms.
  • Use the HTML reference as needed.
05:00

Text

The Elements of Markdown

  • Markdown is designed to be easy to write and easy to read:

    A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions.
    -John Gruber

  • Quarto uses extended version of Pandoc markdown.
  • Pandoc classifies markdown in terms of Inline and Block elements.

Whenever I hear “Pandoc”, I picture . . .


. . . but there’s help!

Which of the following forms of text formatting are possible in pandoc markdown?

  1. italics
  2. bold
  3. underline
  4. superscript
  5. subscript
  6. strikethrough

Inline Elements: Text Formatting

Markdown

Markdown allows you to format text
with *emphasis* and **strong emphasis**.
You can also add superscripts^2^, 
subscripts~2~, and display code 
`verbatim`. Little known fact: you can 
also ~~strikethrough~~ text and present
it in [small caps]{.smallcaps}.

Output

Markdown allows you to format text with emphasis and strong emphasis. You can also add superscripts2, subscripts2, and display code verbatim. Little known fact: you can also strikethrough text and present it in small caps.

Inline Elements: Math

Markdown

The area of a circle is $A = \pi r^2$,
where $r$ is the radius and $\pi$ is
the constant $3.141592\ldots$.

Output

The area of a circle is \(A = \pi r^2\), where \(r\) is the radius and \(\pi\) is the constant \(3.141592\ldots\).



TeX math lives between two $. Opening $ must have a non-space character immediately to its right, while the closing $ must have a non-space character immediately to its left, and must not be followed immediately by a digit.

– the Pandoc Docs

Inline Elements: Footnotes

Markdown

A short note.^[Fits inline.]

Output

A short note.1


A longer footnote[^9]

[^9]:  Can be placed in a separate block.
The id can be any alphanumeric string.

A longer footnote2

Placement of the actual footnote depends on the format: end of page for pdf, end of doc for HTML, bottom of slide for presentations.

Block Elements: Paragraph

One or more lines of text followed by one or more blank lines.

Markdown

Lorem ipsum dolor sit amet,
consectetur adipiscing elit.

Sed do eiusmod tempor.

Output

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Sed do eiusmod tempor.


Without the blank line, the line break is treated as a space.

Lorem ipsum dolor sit amet,
sconsectetur adipiscing elit.
Sed do eiusmod tempor.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor.

Block Elements: Headers

Markdown Syntax Output
# Header 1

Header 1

## Header 2

Header 2

### Header 3

Header 3

#### Header 4

Header 4

##### Header 5
Header 5
###### Header 6
Header 6

Block Elements: Lists

Can use *, -, or + may be used for unordered list items.

Markdown

Unordered list:

* red
* green
* blue

Ordered list:

1. red
1. green
3. blue

Output

Unordered list:

  • red
  • green
  • blue

Ordered list:

  1. red
  2. green
  3. blue


Pandoc gives you a lot of control over lists, including nesting, fancy lists, definition lists, blocks in lists, and example lists.

Which of the following will render to the output on the right?

A

1. I has a sandwich.

   It was deliicous.

1. I had coffee.

   It gave me joy.

C

1. I has a sandwich.
It was deliicous.

2. I had coffee.
It gave me joy.

B

1. I has a sandwich.
  It was deliicous.

2. I had coffee.
  It gave me joy.

D

1. I has a sandwich.

    It was deliicous.

2. I had coffee.

    It gave me joy.

Output

  1. I has a sandwich.

    It was deliicous.

  2. I had coffee.

    It gave me joy.

Block Elements: Lists (blocks in lists)

A list item may contain multiple paragraphs and other block-level content. Subsequent block elements must be preceded by a blank line and indented to line up with the first non-space content after the list marker. – the Pandoc Docs

Markdown

1. First item...

   ...Continued.

1. Second item

   # header

1. Third item

Output

  1. First item…

    …Continued.

  2. Second item

    header

  3. Third item

Block Elements: Lists (example lists)

The first list item with a @ marker will be numbered 1., the next 2., etc. The numbered examples need not occur in a single list; each new list using @ will take up where the last stopped. – the Pandoc Docs

Markdown

(@)  The first example.
(@)  The second example.

Explanation of examples.

(@)  The third example.

Output

  1. The first example.
  2. The second example.

Explanation of examples.

  1. The third example.

You can also label your examples: (@goodname).

Block Elements: Math

Markdown

A larger equation:

$$
f(x)={\sqrt{\frac{\tau}{2\pi}}}
      e^{-\tau (x-\mu )^{2}/2}
$$

This breaks it:

$$

\bar{x} = \sum_{i=i}^n x_1
$$

Output

A larger equation:

\[ f(x)=\sqrt{\frac{\tau}{2\pi}} e^{-\tau (x-\mu )^{2}/2} \]

This breaks it:

$$

{x} = _{i=i}^n x_1 $$

For “display” math, use $$ delimiters.

Block Elements: Images

Block images use the same syntax as inline images.

Markdown

Images are a block element...

![Elephant](images/elephant.png)

or are they?

Output

Images are a block element…

Elephant

or are they?

Screenshot of html output showing the image inside a paragraph block.

Screenshot of latex output showing the image inside a figure environment

Images behave mostly like inline elements but actually live in a block (e.g. a paragraph). Their behavior depends on output format.

Your Turn

Your goal is to create from scratch the beautiful documents 3-markdown-goal.html and 3-markdown-goal.pdf. Add into 3-markdown.qmd the markdown syntax needed to create the various inline and block elements found in the output documents.



Inline

  • text formatting
  • math
  • links and images
  • footnotes

Block

  • paragraphs
  • headers
  • lists
  • math
  • images


10:00

Code Cells

Pandoc’s Fenced Code Block

Sandwich the code between “fences” of at least three backticks1. An optional language provides syntax highlighting.

```cobol
1 + 1
```
  • Useful for displaying source code, not running it
  • Note that the language is not in { }
  • Pandoc supports 140 languages!

R Markdown’s Code Chunk

```{r, echo=FALSE}
rnorm(3)
```


What syntax is being used in echo=FALSE?

  1. HTML
  2. Pandoc attribute syntax
  3. YAML
  4. CSS
  5. R

Generalizing the Code Chunk

How can this be generalized to other languages?

```{r, echo=FALSE}
rnorm(3)
```
  • Executable code flagged by { }

Generalizing the Code Chunk

How can this be generalized to other languages?

```{language, echo=FALSE}
code
```
  • Executable code flagged by { }
  • Support R, Python, Julia
  • Also support mermaid and dot diagram languages1.

Generalizing the Code Chunk

How can this be generalized to other languages?

```{language}
#| echo: false

code
```
  • Executable code flagged by { }
  • Support R, Python, Julia
  • Also support mermaid and dot diagram languages1
  • Cell options live as YAML inside the cell after #| (the hash pipe!)2

This is a Quarto Code Cell.

The Perks of the Hashpipe #|

  1. Line breaks prevent chunk options that go on {r, and=on, and=on, and=on, and=on, and=on, and=on}
  1. Chunk options are now pan-language with <commentchar>|.
```{python}
#| echo: false
```
```{mermaid}
%%| echo: false
```
  1. No more yelling! (eval=FALSE)

Execution Options

Control how the code is executed with options.

Option Description
eval Evaluate the code chunk (if false, just echos the code into the output).
echo Include the source code in output
output Include the results of executing the code in the output (true, false, or asis to indicate that the output is raw markdown and should not have any of Quarto’s standard enclosing markdown).
warning Include warnings in the output.
error Include errors in the output.
include Catch all for preventing any output (code or results) from being included (e.g. include: false suppresses all output from the code block).

Setting knitr options

The knitr syntax for passing options still works since Quarto uses knitr.

Source

```{r, error=TRUE}
#| echo: true

rnorm(5       # this is missing a parens
```

Output

rnorm(5       # this is missing a parens
Error: <text>:2:0: unexpected end of input
1: rnorm(5       # this is missing a parens
   ^

While it’s possible to use R chunks options, hash pipe options are more portable across computational engines.


Don’t forget to use tab-completion to see the available options!


From Cell Option to YAML

---
title: My Doc
format: html
---

```{r}
#| echo: true

pi + 1
```

From Cell Option to YAML

---
title: My Doc
format: html
execute:
  echo: true
---

```{r}
pi + 1
```
  • Options can be moved into YAML under the execute key to apply to all chunks. Exceptions to that option can be set cell-by-cell.

From Cell Option to YAML

---
title: My Doc
format: html
execute:
  echo: true
knitr:
  opts_chunk: 
    collapse: true
---

```{r}
pi + 1
```
  • Options can be moved into YAML under the execute key to apply to all chunks. Exceptions to that option can be set cell-by-cell.

  • You can also pass options via YAML to knitr through the knitr key1.

From Cell Option to YAML

---
title: My Doc
format: html
execute:
  echo: true
knitr:
  opts_chunk: 
    collapse: true
    R.options:
      digits: 2
---

```{r}
pi + 1
```
  • Options can be moved into YAML under the execute key to apply to all chunks. Exceptions to that option can be set cell-by-cell.

  • You can also pass options via YAML to knitr through the knitr key1.

  • You can use knitr to pass options that control your R session.

Example: Figures from Code

```{r}
library(palmerpenguins)
library(ggplot2)

ggplot(penguins,
       aes(x = bill_length_mm,
           y = bill_depth_mm,
           col = island)) +
  geom_point()
```

Example: Figures from Code

```{r}
#| fig-width: 5
#| fig-height: 3

library(palmerpenguins)
library(ggplot2)

ggplot(penguins,
       aes(x = bill_length_mm,
           y = bill_depth_mm,
           col = island)) +
  geom_point()
```

Save time/code by moving figure sizing defaults up to the YAML.

Your turn

  • Open 3-code-cells.qmd and render the document.
  • Add echo: false to the code cell and re-render.
  • Add 2 more cell options by using Ctrl + Space after the #| or consult the Quarto Reference.
  • Add a second code cell (you can copy + paste the first), move your cell options to the YAML, and re-render.
  • Please share your favorite code cell option on .
07:00

Questions

Any questions / anything you’d like to review before we wrap up this module?

One last thing!

Where does the name “Quarto” come from?

Let’s take a break!



30:00

References and further reading