16  Reproducible Documents with Quarto

NoteLearning Objectives

After completing this chapter, you will be able to:

  • Explain the benefits of literate programming for reproducible research
  • Create Quarto documents that combine code, text, and results
  • Use Markdown syntax for text formatting
  • Configure document settings with YAML headers
  • Control code execution and output with chunk options
  • Include mathematical equations and figures
  • Run Python (and mixed R/Python) code in a Quarto document
  • Use callouts, tabsets, divs, and cross-references to structure a document
  • Cite sources from a BibTeX file
  • Render documents to multiple output formats from your IDE (VS Code, Positron, or RStudio) and the command line

16.1 What is Quarto?

Quarto is an open-source scientific publishing system that enables you to create dynamic documents combining narrative text, code, and results (Posit Software, PBC, 2024). It represents the next generation of literate programming tools, building on the legacy of R Markdown (Xie et al., 2018) while extending support to multiple programming languages including R, Python, Julia, and Observable JavaScript.

The name “Quarto” comes from the Latin word for a quarter sheet of paper folded twice to create an eight-page booklet—an evocative reference to the history of publishing and scholarly communication. Just as the quarto format revolutionized book publishing in the 16th century, the Quarto system is revolutionizing how scientists share their work.

Quarto documents are plain text files with the .qmd extension that can be rendered to:

  • HTML documents and websites
  • PDF documents
  • Microsoft Word documents
  • Presentations (PowerPoint, reveal.js)
  • Books (like this one!)
  • Interactive dashboards

Why Use Quarto?

Quarto solves fundamental problems in scientific communication:

Reproducibility
Your analysis and its documentation live together. Anyone can re-run your code and verify your results.
Efficiency
No more copying and pasting results between applications. Update your data, re-render, and all figures and statistics update automatically.
Transparency
Readers can see exactly how results were generated. The code is the methods section.
Collaboration
Plain text files work seamlessly with version control systems like Git (Chapter 19).
Flexibility
Write once, render to multiple formats. The same document can produce a lab report, a presentation, and a web page.
Tip

This entire textbook was written in Quarto! You can see the source files in the repository.

The Literate Programming Philosophy

Quarto is built on the concept of literate programming, introduced by Donald Knuth in 1984 (Knuth, 1984). The idea is revolutionary yet simple: instead of writing code with occasional comments, write a human-readable document that happens to contain executable code. As Knuth wrote:

“Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do.”

In practice, this means your analysis scripts become documents that tell a story. The code is woven together with explanations of why you’re doing each step, what you expect to find, and how the results should be interpreted. When you share this document, readers understand not just the mechanical steps, but the reasoning behind each analytical choice.

This approach has profound implications for science:

  1. Your methods become self-documenting. No more separate “methods” documents that drift out of sync with your actual code.

  2. Errors become visible. When code and narrative live together, inconsistencies between what you say you’re doing and what you’re actually doing become obvious.

  3. Learning accelerates. Well-documented analyses serve as tutorials for others (and for your future self) who want to learn your techniques.

  4. Reproducibility becomes the default. Rendering re-runs everything from raw data to final figures, so “can we regenerate this?” stops being a scramble before submission and becomes something that happens every time you press render.

NoteLiterate programming is FAIR practice

Funders increasingly require that research outputs be FAIR — Findable, Accessible, Interoperable, and Reusable (Wilkinson et al., 2016) — and a literate document delivers each letter in practice. Plain-text .qmd sources and tidy data tables are open formats that every tool can read (interoperable); the methods travel inside the document instead of drifting in a separate file (reusable); and the whole bundle — source, data, and environment — can be deposited in a public repository with a persistent identifier (findable and accessible; Chapter 19). Appendix C works through the principles and a minimal FAIR checklist; Chapter 1 describes the funding policies behind them.

16.2 Markdown: The Foundation

Markdown is a lightweight markup language that lets you add formatting to plain text. Created by John Gruber in 2004, it’s designed to be readable in its raw form while rendering to beautifully formatted documents.

Why Markdown?

Markdown’s appeal lies in its simplicity—there are no complex menus or formatting palettes to learn. You write plain text with a few special characters, and the formatting appears when the document renders. This simplicity makes Markdown incredibly portable: your files work on any computer, in any text editor, without special software. Because Markdown files are plain text, they’re also future-proof—unlike proprietary formats that may become obsolete, text files will always be readable. Finally, plain text is version-control friendly: Git can track every change you make, showing exactly what was added, removed, or modified between versions.

NoteSource mode and the visual editor

Positron, RStudio, and VS Code can each show a Markdown or Quarto file in two ways: source mode, the raw text exactly as it is stored, and a visual editor that renders headings, bold, and tables as you type, like a lightweight word processor (look for the toggle at the top right of the editor). Both edit the same plain-text file, so nothing is lost by switching back and forth. Learn source mode first—it is what this chapter teaches, what Git shows when files change, and what you will see in everyone else’s files—and reach for the visual editor where it shines: editing tables and inserting citations.

Basic Text Formatting

*italic text* or _italic text_

**bold text** or __bold text__

***bold and italic*** or ___bold and italic___

~~strikethrough text~~

`inline code`

Renders as:

italic text or italic text

bold text or bold text

bold and italic or bold and italic

strikethrough text

inline code

Headers

Create hierarchical structure with headers:

# Header 1 (Chapter title)
## Header 2 (Section)
### Header 3 (Subsection)
#### Header 4 (Sub-subsection)
Tip

In Quarto books, each chapter typically starts with a single # header, with subsequent sections using ## and ###.

Lists

Unordered lists use asterisks, hyphens, or plus signs:

- Item one
- Item two
  - Nested item (indent with 2 spaces)
  - Another nested item
- Item three
  • Item one
  • Item two
    • Nested item (indent with 2 spaces)
    • Another nested item
  • Item three

Ordered lists use numbers:

1. First step
2. Second step
3. Third step
   1. Sub-step
   2. Another sub-step
  1. First step
  2. Second step
  3. Third step
    1. Sub-step
    2. Another sub-step

Task lists add a checkbox to each item (rendered in HTML output):

- [ ] Incomplete task
- [x] Completed task

Blockquotes

> This is a blockquote. Use it for quotations
> or to highlight important text.
>
> Multiple paragraphs work too.

This is a blockquote. Use it for quotations or to highlight important text.

Multiple paragraphs work too.

Code Blocks

For displaying code without execution, use fenced code blocks with language specification:

```python
def hello():
    print("Hello, World!")
```
def hello():
    print("Hello, World!")

Tables

Create tables with pipes and hyphens (the result is Table 16.1):

| Column 1 | Column 2 | Column 3 |
|:---------|:--------:|---------:|
| Left     | Center   | Right    |
| aligned  | aligned  | aligned  |
Table 16.1: A rendered pipe table with left, center, and right alignment
Column 1 Column 2 Column 3
Left Center Right
aligned aligned aligned

The colons indicate alignment: :--- left, :---: center, ---: right.

Tables produced by code. Most tables in a report come from a code chunk rather than being typed by hand. Give the chunk a label starting with tbl- and a tbl-cap, and the table becomes numbered and cross-referenceable exactly like a hand-written one:

```{r}
#| label: tbl-mtcars-head
#| tbl-cap: "First rows of the mtcars dataset"
knitr::kable(head(mtcars[, 1:4]))
```
```{python}
#| label: tbl-df-head
#| tbl-cap: "First rows of the data frame"
from IPython.display import Markdown
Markdown(df.head(6).to_markdown())   # df is a pandas DataFrame
```

knitr::kable() is the simplest R option; the gt package (used throughout Chapter 14) produces publication-quality tables from the same pipeline.

Horizontal Rules

Create a horizontal divider with three or more hyphens, asterisks, or underscores:

---

Footnotes

Add footnotes for additional context without interrupting the flow:

This is a statement that needs a citation.[^1]

[^1]: This is the footnote content.

This is a statement that needs a citation.1

Definition Lists

Define terms with a colon-based syntax:

Term 1
:   Definition of the first term.

Term 2
:   Definition of the second term.
:   You can have multiple definitions.
Term 1
Definition of the first term.
Term 2
Definition of the second term.
You can have multiple definitions.

Line Breaks and Paragraphs

In Markdown, a single line break is ignored—you need a blank line to create a new paragraph. To force a line break without a new paragraph, end the line with two spaces or use <br>.

Table 16.2 collects the syntax introduced above.

TipMarkdown Formatting Quick Reference
Table 16.2: Markdown formatting quick reference
Format Syntax Result
Bold **text** text
Italic *text* text
Code `code` code
Link [text](url) text
Strikethrough ~~text~~ text
Subscript H~2~O H2O
Superscript 10^2^ 102

16.3 Quarto Document Structure

A Quarto document has three main parts:

  1. YAML Header: Document metadata and settings
  2. Markdown Content: Text and formatting
  3. Code Chunks: Executable code blocks

YAML Header

The YAML header appears at the top of the document, enclosed by triple dashes:

---
title: "My Analysis Report"
author: "Your Name"
date: today
format: html
---

YAML stands for “YAML Ain’t Markup Language” (a recursive acronym). It uses key-value pairs with consistent indentation.

Common YAML Options

---
title: "Genomic Analysis Report"
author: "Jane Scientist"
date: "2025-01-15"
format:
  html:
    theme: cosmo
    toc: true
    toc-depth: 3
    number-sections: true
    code-fold: true
execute:
  echo: true
  warning: false
  message: false
bibliography: references.bib
---
Table 16.3: Common YAML header options
Option Description
title Document title
author Author name(s)
date Publication date (today for current date, or "2025-01-15")
format Output format(s)
toc Include table of contents
toc-depth How many header levels in TOC
number-sections Number the section headings
code-fold Collapse code by default
execute Global code execution options (echo, warning, message, …)
bibliography BibTeX file for citations (Section 16.10)
Warning

YAML is indentation-sensitive: nested options must be indented with spaces (never tabs), and a colon must be followed by a space. An error such as “YAML parse exception” almost always means a mis-indented line or a missing quote around a value that contains a colon.

16.4 Code Chunks

Code chunks are the heart of Quarto’s power—they let you embed executable code directly in your document.

Basic Syntax

In Quarto, code chunks use this syntax:

```{r}
# Your R code here
mean(c(1, 2, 3, 4, 5))
```
# Your R code here
mean(c(1, 2, 3, 4, 5))
#> [1] 3

Chunk Options

Control chunk behavior with special comments starting with #|:

```{r}
#| label: calculate-mean
#| echo: true
#| eval: true

data <- c(1, 2, 3, 4, 5)
mean(data)
```

Essential Chunk Options

The options you will use most are listed in Table 16.4.

Table 16.4: Code chunk options
Option Description Default
echo Show code in output true
eval Execute the code true
include Include chunk in output true
output Show results true
warning Show warnings true
message Show messages true
error Continue on error false
cache Cache results false
label Name the chunk (and its cross-reference id) none
fig-cap / tbl-cap Caption a figure / table none
code-fold Collapse the code behind a toggle false
echo: fenced Show the chunk with its fence and options (for teaching) —

Set defaults for every chunk in the YAML execute: block (Table 16.3) and override per chunk only where needed. A hidden setup chunk at the top of a document is typically #| include: false.

Controlling Output

```{r}
#| label: output-examples

# echo: true shows this code
x <- rnorm(100)
summary(x)
```
#>     Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
#> -2.58685 -0.82420  0.06269 -0.05193  0.60584  2.49475

Hide code, show results (great for final reports):

Figure 16.1: Output of a chunk rendered with echo: false: the histogram appears but the code does not

Show code, hide results (for teaching):

# This code is displayed but not executed
install.packages("new_package")  # Don't actually run this

Figure Options

Control figure appearance with the options in Table 16.5; Figure 16.2 below is produced by such a chunk:

library(ggplot2)
ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point(color = "steelblue", size = 3) +
  geom_smooth(method = "lm", se = FALSE, color = "coral") +
  labs(x = "Weight (1000 lbs)", y = "Miles per Gallon") +
  theme_minimal()
Figure 16.2: A demonstration plot with custom dimensions
Table 16.5: Figure chunk options
Option Description
fig-cap Figure caption
fig-width Width in inches
fig-height Height in inches
fig-align Alignment: left, center, right
out-width Output width (e.g., “80%”)
fig-dpi Resolution of raster output (e.g., 300 for print)
fig-format Format: png, svg, pdf
fig-subcap List of sub-captions for a chunk that draws several plots
layout-ncol Number of columns to arrange multiple plots in

Subfigures. A chunk that produces more than one plot can label each with fig-subcap and arrange them with layout-ncol; the panels are referenced as @fig-label-1, @fig-label-2, and so on:

```{r}
#| label: fig-distributions
#| fig-cap: "Two simulated distributions"
#| fig-subcap:
#|   - "Normal"
#|   - "Exponential"
#| layout-ncol: 2

hist(rnorm(1000))
hist(rexp(1000))
```

Compare @fig-distributions-1 with @fig-distributions-2.

Inline Code

A computed value does not need a whole chunk. An inline expression—a short piece of code inside a sentence—is evaluated at render time and its result typeset in place:

We measured `{r} nrow(stickle)` fish across `{r} n_distinct(long$gene)` genes.
Two plus two is `{python} 2 + 2`.

This is the mechanism behind the promise that numbers in your prose can never disagree with your data: “We measured 80 fish” is computed, not typed, so re-rendering after the data change updates the sentence along with every figure (Section 16.18 shows it in action). Older knitr documents write the R form without the braces—the expression follows r directly after the opening backtick; both forms work in Quarto. Keep inline expressions to a single short call—compute anything substantial in a chunk, store it in a variable, and reference the variable inline.

16.5 Python in Quarto

Everything above works unchanged for Python: replace {r} with {python} and the chunk runs when the document renders. The mechanics differ in one respect. R chunks are executed by the knitr engine, which ships with R; Python chunks are executed by the Jupyter engine, so you need a Python environment with Jupyter installed (Section 12.3):

pip install jupyter matplotlib pandas     # inside your project's virtual environment
quarto check jupyter                      # confirms Quarto can find it

Quarto chooses the engine from the first chunk it sees, or you can state it in the YAML header:

---
title: "GC Content Report"
jupyter: python3
---
```{r}
#| label: gc-r
seqs <- c("ATGCGCGATATCG", "GGCCTTAA")
gc <- function(s) {
  bases <- strsplit(s, "")[[1]]
  mean(bases %in% c("G", "C"))
}
round(sapply(seqs, gc), 3)
```
```{python}
#| label: gc-py
seqs = ["ATGCGCGATATCG", "GGCCTTAA"]
def gc(s):
    return sum(b in "GC" for b in s) / len(s)
{s: round(gc(s), 3) for s in seqs}
```

A {python} chunk accepts the same #| options as an R chunk (echo, eval, fig-cap, label, and so on), and a matplotlib or seaborn figure produced in a chunk labelled fig-... with a fig-cap becomes a cross-referenceable figure exactly as a ggplot does.

Mixing R and Python in one document. A document can use only one engine, but the knitr engine can run Python chunks through the reticulate R package: install.packages("reticulate"), then {python} chunks in an otherwise-R document execute in a Python session, and objects pass between languages as py$name (in R) and r.name (in Python). This is the route to take when most of a document is R and a step or two is Python.

Jupyter notebooks. Quarto also renders .ipynb files directly, so an existing notebook needs no conversion:

quarto render analysis.ipynb                     # render the notebook as is
quarto render analysis.ipynb --to pdf
quarto convert analysis.ipynb                    # produce analysis.qmd from it
quarto convert analysis.qmd                      # and back again

By default Quarto uses the outputs already stored in the notebook; add --execute to re-run it during rendering. Section 2.9 compares the two formats, and Chapter 12 introduces the Python language itself.

16.6 Mathematical Equations

Quarto supports LaTeX math notation for equations; Chapter 17 covers the notation in depth, and Appendix G is a symbol reference.

Inline Math

Use single dollar signs for inline equations:

The mean is calculated as $\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i$.

The mean is calculated as \(\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i\).

Display Math

Use double dollar signs for centered equations:

$$
\sigma^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i - \bar{x})^2
$$

\[ \sigma^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i - \bar{x})^2 \]

Common Math Notation

Table 16.6 lists the constructs you will need most often.

Table 16.6: Common LaTeX math notation
Symbol Code Result
Greek letters $\alpha, \beta, \gamma$ \(\alpha, \beta, \gamma\)
Subscript $x_1, x_{12}$ \(x_1, x_{12}\)
Superscript $x^2, x^{10}$ \(x^2, x^{10}\)
Fraction $\frac{a}{b}$ \(\frac{a}{b}\)
Square root $\sqrt{x}$ \(\sqrt{x}\)
Sum $\sum_{i=1}^{n}$ \(\sum_{i=1}^{n}\)
Product $\prod_{i=1}^{n}$ \(\prod_{i=1}^{n}\)
Integral $\int_0^1 f(x)dx$ \(\int_0^1 f(x)dx\)

Example: Statistical Formulas

The probability density function of a normal distribution:

\[ f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2} \]

A regression equation:

\[ Y_i = \beta_0 + \beta_1 X_{1i} + \beta_2 X_{2i} + \epsilon_i \]

16.7 Callout Blocks

Quarto provides special callout blocks for highlighting information:

::: {.callout-note}
This is a note callout for additional information.
:::

::: {.callout-warning}
This warns readers about potential issues.
:::

::: {.callout-important}
This highlights critical information.
:::

::: {.callout-tip}
This provides helpful tips.
:::

::: {.callout-caution}
This urges caution.
:::

::: {.callout-tip title="A custom title"}
Add `title="..."` for your own heading.
:::

::: {.callout-note collapse="true"}
Add `collapse="true"` and the box starts folded; click to open.
:::
Note

This is a note callout for additional information.

Warning

This warns readers about potential issues.

Tip

This provides helpful tips.

This one starts folded. Collapsed callouts are handy for optional detail or exercise answers.

The five types differ only in icon and color; pick by meaning (Table 16.7).

Table 16.7: Quarto callout types
Type Color Use for
note Blue Supplementary information
tip Green Helpful suggestions and shortcuts
warning Orange Potential problems or common mistakes
important Red Information the reader must not miss
caution Red Dangerous or irreversible operations

A callout is a fenced div: a line of three or more colons with the class in braces, the content, and a closing line of colons. The opening and closing fences must each sit on their own line with a blank line around the block, or the div will not close and the rest of the page renders inside the box.

16.8 Tabsets, Divs, and Spans

The same ::: fence syntax gives you several other structures.

Tabsets present alternatives (R vs. Python, source vs. output) in tabs. Every heading inside the div becomes a tab:

::: {.panel-tabset}
### R

```{r}
mean(1:10)
```

### Python

```{python}
sum(range(1, 11)) / 10
```
:::

Layout divs arrange their children. {layout-ncol=2} places two figures side by side; {.column-margin} pushes content into the margin; {.column-page} lets a wide table use the full page width:

::: {layout-ncol=2}
![Control](images/control.png)

![Treatment](images/treatment.png)
:::

Generic attributes in braces can follow any div, heading, image, or code block: an id (#name), classes (.name), and key-value pairs. This is how headings get cross-reference ids and how images get sizes and alt text:

## Methods {#sec-methods}

![Clusters on a UMAP](images/umap.png){#fig-umap width="80%" fig-alt="UMAP coloured by cluster"}

::: {.callout-warning collapse="true"}
:::

Spans apply attributes to a run of inline text with [text]{...}:

This is [highlighted]{.mark} and this is [small]{.smallcaps}.
Print-only text: [see the online version]{.content-visible when-format="pdf"}

Nested divs need more colons on the outside (:::: around :::) so that Quarto can tell which fence closes which block.

16.9 Cross-References

Reference figures, tables, and sections:

Figures and Tables

See @fig-example for the scatter plot.
The options are listed in @tbl-chunk-options.

See Figure 16.2 for the scatter plot. The options are listed in Table 16.4.

Sections

## Results {#sec-results}

As shown in @sec-results, the treatment effect...

As discussed in Chapter 16, Quarto enables reproducible documents.

The label prefix determines the reference type (Table 16.8). A code chunk becomes a referenceable figure when its label starts with fig- and it has a fig-cap; Markdown tables take their id from the caption line : Caption {#tbl-id}. Quarto numbers everything automatically, so inserting a figure renumbers the rest.

Table 16.8: Cross-reference prefixes
Type Prefix Where the id goes Reference
Figure fig- #| label: fig-name or ![...](f.png){#fig-name} @fig-name
Subfigure fig- fig-subcap panels of fig-name @fig-name-1
Table tbl- #| label: tbl-name or : Caption {#tbl-name} @tbl-name
Section sec- ## Heading {#sec-name} @sec-name
Equation eq- $$ ... $$ {#eq-name} @eq-name
Code listing lst- #| label: lst-name with lst-cap @lst-name

Quarto also recognises thm-, lem-, def-, exm-, and exr- for theorem-style blocks (::: {#thm-clt}). Capitalize the prefix (@Fig-name) to begin a sentence with “Figure” rather than “fig.”

Equations

$$
y_{gc} \sim \text{NB}(\mu_{gc}, \phi_g)
$$ {#eq-nb}

As @eq-nb states, counts follow a negative binomial.

The label must sit on the same line as the closing $$, separated by a space. Only labelled equations are numbered. Section 17.13 shows how to align a multi-line derivation under one number.

16.10 Citations

Quarto handles references the same way it handles cross-references: each source has a key, and you cite the key with @. The keys live in a BibTeX file (.bib), a plain-text database in which each entry looks like this:

@article{knuth1984literate,
  author  = {Knuth, Donald E.},
  title   = {Literate Programming},
  journal = {The Computer Journal},
  volume  = {27},
  number  = {2},
  pages   = {97--111},
  year    = {1984}
}

Name the file in the YAML header, then cite by key:

---
title: "Report"
bibliography: references.bib
---

Knuth introduced literate programming [@knuth1984literate].
@knuth1984literate argued that programs should be written for people.
Several authors agree [@knuth1984literate; @xie2018r].
A page reference [@knuth1984literate, p. 99] or a prefix [see @knuth1984literate].

Bracketed citations render in parentheses, “(Knuth 1984)”; a bare @key renders in the running text, “Knuth (1984)”. Quarto compiles a reference list at the end of the document automatically, or wherever you place a ::: {#refs} div. The default style is Chicago author-date; add csl: apa.csl (any style file from the CSL repository) to change it.

Tip

Reference managers such as Zotero export BibTeX directly, and Google Scholar’s “Cite” button offers a BibTeX entry for any paper. Keep one references.bib per project and let it grow.

16.11 Rendering Documents

Rendering is the step that turns the plain-text source into a finished document. Quarto reads the .qmd file, runs every code chunk through R or Python (via knitr or Jupyter), weaves the results into the Markdown, and hands the whole thing to Pandoc, which produces the output format you asked for (Figure 16.3). Because the code runs every time, the numbers, tables, and figures in the output can never drift away from the code that produced them.

Figure 16.3: From source to document: one .qmd file, run through Quarto, becomes an HTML page, a PDF (via LaTeX), a Word document, or a slide deck.

From VS Code, Positron, or RStudio

  • Click the Preview button (VS Code and Positron, Quarto extension) or the Render button (RStudio), or
  • Use the keyboard shortcut, the same in all three: Ctrl+Shift+K (Windows/Linux) or Cmd+Shift+K (Mac)

While writing, Ctrl+Alt+I / Cmd+Option+I inserts a new code chunk and Ctrl+Shift+Enter / Cmd+Shift+Enter runs the current chunk without rendering the whole document (more in Appendix A).

ImportantWorks in the console, fails on render

Rendering starts a fresh session and runs the document top to bottom, so nothing from your interactive session—packages you loaded by hand, objects you created at the console, a chunk you ran and then deleted—exists during the render. This is the most common Quarto surprise: a chunk that “just worked” interactively fails with object not found or could not find function when you render. It is a feature, not a bug: a successful render is proof that the document is self-contained and your analysis actually reproducible. The habits that follow from it: load every package in the document’s first chunk, create everything the document uses inside the document, and render early and often rather than once at the deadline, so problems surface one at a time.

From Command Line

# Render to default format
$ quarto render document.qmd

# Render to specific format
$ quarto render document.qmd --to pdf

# Render all documents in a project
$ quarto render

Live Preview

For interactive editing:

$ quarto preview document.qmd

This opens a browser window that automatically updates as you edit. --port 8080 fixes the port and --no-browser prints the URL instead of opening a window (useful on a remote machine).

The Quarto Command Line

The quarto program has a handful of subcommands you will use regularly (Table 16.9).

Table 16.9: Common Quarto command-line commands
Command What it does
quarto render file.qmd Render to the document’s default format
quarto render file.qmd --to pdf Render to one format (html, pdf, docx, revealjs, …)
quarto render file.qmd --to all Render every format listed in the YAML
quarto render file.qmd --output out.html Choose the output file name
quarto render file.qmd -P n:100 Set a document parameter (params: in YAML)
quarto render Render the whole project (_quarto.yml)
quarto preview file.qmd Live preview that re-renders on save
quarto create project Scaffold a new project, website, or book
quarto check Verify the installation (R, Python/Jupyter, LaTeX)
quarto install tinytex Install a minimal LaTeX so PDF rendering works
quarto publish gh-pages Publish the rendered site (see Section 19.11)
quarto --version Print the installed version

16.12 Multiple Output Formats

Render to multiple formats from one source:

---
title: "My Report"
format:
  html:
    theme: cosmo
  pdf:
    documentclass: article
  docx: default
---

Then render all formats:

$ quarto render document.qmd --to all

Without --to all, quarto render produces only the first format listed. Each format accepts its own options, nested under its name.

HTML Options

HTML is the richest target: it supports folding code, tabsets, interactive figures, and a floating table of contents.

format:
  html:
    toc: true
    toc-depth: 3
    toc-location: left
    number-sections: true
    code-fold: true
    code-tools: true
    theme: cosmo
    embed-resources: true
Table 16.10: Common HTML format options
Option Description Values
toc-location Where the TOC sits left, right, body
code-fold Collapse code behind a toggle true, false, show
code-tools Menu to view/copy the full source true, false
theme Bootswatch visual theme default, cosmo, flatly, darkly, …
embed-resources Bundle images, CSS, and JS into one .html file true, false

embed-resources: true is the option to remember when you email a report: without it the HTML file depends on a folder of supporting files that must travel with it.

PDF Options

PDF output passes through LaTeX (Chapter 17), so a LaTeX installation is required (quarto install tinytex provides a small one).

format:
  pdf:
    documentclass: article
    geometry:
      - margin=1in
    fontsize: 11pt
    number-sections: true
    colorlinks: true
    keep-tex: false
Table 16.11: Common PDF format options
Option Description Values
documentclass LaTeX document class article, report, book
geometry Page size and margins margin=1in, letterpaper, …
fontsize Body text size 10pt, 11pt, 12pt
colorlinks Colored rather than boxed hyperlinks true, false
keep-tex Keep the intermediate .tex file for debugging true, false

Word Options

Word output is the format collaborators without Quarto can edit. A reference document supplies the styles (fonts, heading sizes, margins) that the generated .docx inherits, so a journal’s or lab’s template can be applied without touching the source:

format:
  docx:
    toc: true
    number-sections: true
    reference-doc: lab-template.docx

Run quarto pandoc -o custom-reference.docx --print-default-data-file reference.docx to obtain a starting template, edit its styles in Word, and point reference-doc at the result.

16.13 Presentations with RevealJS

Set format: revealjs and the same machinery — Markdown, chunks, callouts, math, cross-references — produces a browser-based slide deck instead of a page. The course’s lecture slides are built exactly this way.

---
title: "My Research in Six Slides"
author: "Your Name"
format:
  revealjs:
    theme: default        # simple, serif, moon, solarized, dark, ...
    slide-number: true
    footer: "Lab meeting - November 2026"
    incremental: false    # true = every list reveals point by point
    chalkboard: true      # draw on your slides while presenting
---

The structure rules are simple: every level-2 heading (##) starts a new slide, and a level-1 heading (#) makes a section-divider slide. Beyond that, a handful of presentation-specific tools cover most of what a scientific talk needs:

Revealing content stepwise. Wrap a list in ::: {.incremental} to step through it with the arrow key, or put three spaced dots on their own line (. . .) to pause anything mid-slide. Any block with the .fragment class appears on a keypress.

Columns. A :::: columns div containing two ::: {.column width="45%"} divs puts text beside a figure, or two figures side by side — the most common slide layout in a research talk.

Executed code on slides. Chunks run at render time exactly as in documents, so a figure on a slide is regenerated from data on every render. Two chunk options earn their keep in decks: output-location: slide puts a chunk’s figure on its own slide, and code-line-numbers: "1-2|4|6" highlights groups of lines one keypress at a time — ideal for walking an audience through code.

Speaker notes. A ::: {.notes} div at the end of a slide is invisible to the audience; press S while presenting for the speaker view with notes and a timer. Press O for a zoomed-out overview of the whole deck, F for fullscreen.

The same source also renders to PowerPoint (quarto render deck.qmd --to pptx) or LaTeX Beamer (--to beamer) when a conference insists; simple layouts survive the trip best.

TipA deck to take apart

The Week 7 example example_slides.qmd on the course Example Files page demonstrates all of the above in twelve compact slides. Render it, press S and O to try the presenter tools, then change the theme in the YAML and render again.

16.14 Scholarly Manuscripts

A journal manuscript is a Quarto document with three extra ingredients: scholarly front matter, a citation style, and the discipline of echo: false.

Scholarly front matter. Authors can be structured objects rather than plain strings, carrying affiliations, ORCID iDs, and the corresponding-author flag; abstract and keywords complete the title page:

---
title: "Matrix stiffness tunes gene expression in the gut"
author:
  - name: Avery J. Rivers
    orcid: 0000-0002-1825-0097
    corresponding: true
    email: arivers@uoregon.edu
    affiliations:
      - ref: kc
affiliations:
  - id: kc
    name: University of Oregon
    department: Knight Campus for Accelerating Scientific Impact
abstract: |
  One paragraph, 150-200 words, no citations.
keywords: [extracellular matrix, mechanotransduction]
---

Results, never code. Set echo: false document-wide (under execute: in the YAML): readers of a manuscript see figures, tables, and numbers — all still regenerated from the embedded code on every render, with inline code keeping the values in your sentences honest (Section 16.4.6).

Citations in the journal’s style. Name a .bib file and a CSL style file in the YAML (Section 16.10) and every citation and the reference list are formatted for that journal — nature.csl gives numbered superscripts, apa.csl gives author-year, and the CSL repository has a file for essentially every journal. Changing journals means changing one line, not re-typing references.

Everything numbered and cross-referenced. Figures, tables, display equations ($$ ... $$ {#eq-...}), and sections all take labels and @-references (Section 16.9), so “Equation 2” and “Figure 3” renumber themselves when reviewers ask you to reorder.

Two PDF-specific notes. First, journals often want line numbers on submissions — add \usepackage{lineno} and \linenumbers through include-in-header. Second, Quarto’s default PDF template prints author names but silently drops affiliations; the fix is either a small template-partials file that rebuilds the title block, or a ready-made journal format extension (quarto add quarto-journals/nature and friends — see the journal formats gallery).

TipA manuscript to take apart - and to build on

The Week 7 example example_manuscript.qmd on the course Example Files page is a complete Science/Nature-style article: scholarly front matter, lorem-ipsum sections, inline and display LaTeX, numbered equations, cross-references everywhere, superscript citations from its companion example_manuscript.bib and nature.csl, and a commented title.tex partial that restores affiliations on the PDF title page. It is the intended skeleton for your term project report — copy it, keep the companion files beside it, and replace the lorem ipsum with your science.

16.15 Project Organization

For multi-document projects (like this book), use a _quarto.yml file:

project:
  type: book
  output-dir: docs

book:
  title: "My Analysis Book"
  author: "Your Name"
  chapters:
    - index.qmd
    - intro.qmd
    - methods.qmd
    - results.qmd
    - references.qmd

format:
  html:
    theme: cosmo

16.16 Websites

A Quarto website is a project whose pages share a navigation bar: set type: website in _quarto.yml, and every .qmd in the folder becomes a page of the site. This is how the course website — and a typical personal academic site — is built.

project:
  type: website
  output-dir: docs        # render into docs/ for GitHub Pages

website:
  title: "Avery Rivers"
  navbar:
    left:
      - href: index.qmd
        text: Home
      - research.qmd
      - publications.qmd
      - cv.qmd

format:
  html:
    theme: flatly

Two conveniences do most of the work. About pages: adding an about: block (template trestles, jolla, solana, …) to index.qmd lays out a landing page with your photo, a bio, and link buttons to GitHub, Google Scholar, and email — no HTML required. Live preview: quarto preview run inside the folder serves the site locally and re-renders every time you save, so you edit with the result in view; quarto render writes the finished site into output-dir.

A rendered website is just a folder of HTML — the missing step is hosting, and that is Week 8: push the folder to GitHub and serve it with GitHub Pages (Section 19.11), either from docs/ on the main branch or with quarto publish gh-pages.

TipA site to make your own

The Week 7 example example_website.zip on the course Example Files page is a complete four-page academic site for a fictional graduate student — home/about, research, publications, CV — pre-configured with output-dir: docs for GitHub Pages. Unzip it, run quarto preview inside it, replace Avery’s details with yours, and keep it: it goes live in Week 8.

16.17 Best Practices

Document Structure

  1. Start with clear objectives: What should readers learn?
  2. Organize hierarchically: Use headers to create logical sections
  3. Balance code and narrative: Explain the “why” not just the “what”
  4. Use meaningful chunk labels: #| label: fig-gene-expression not #| label: chunk1

Code Quality

  1. Show relevant code: Hide boilerplate, show analysis
  2. Comment your code: Explain complex operations
  3. Use consistent style: Follow a style guide (tidyverse, etc.)
  4. Set global options: Configure defaults in YAML, override as needed

Reproducibility

  1. Document your environment: Include package versions
  2. Use relative paths: Avoid /Users/yourname/...
  3. Set a random seed: For reproducible random operations
  4. Version control: Track your .qmd files with Git (Chapter 19); GitHub Pages can publish the rendered site (Section 19.11)
# Document your R environment
sessionInfo()
#> R version 4.6.0 (2026-04-24)
#> Platform: aarch64-apple-darwin23
#> Running under: macOS 27.0.1
#> 
#> Matrix products: default
#> BLAS:   /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRblas.0.dylib 
#> LAPACK: /Library/Frameworks/R.framework/Versions/4.6/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.1
#> 
#> locale:
#> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
#> 
#> time zone: America/Los_Angeles
#> tzcode source: internal
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#>  [1] gt_1.3.0        lubridate_1.9.5 forcats_1.0.1   stringr_1.6.0  
#>  [5] dplyr_1.2.1     purrr_1.2.2     readr_2.2.0     tidyr_1.3.2    
#>  [9] tibble_3.3.1    ggplot2_4.0.3   tidyverse_2.0.0
#> 
#> loaded via a namespace (and not attached):
#>  [1] Matrix_1.7-5       gtable_0.3.6       jsonlite_2.0.0     compiler_4.6.0    
#>  [5] tidyselect_1.2.1   xml2_1.5.2         splines_4.6.0      scales_1.4.0      
#>  [9] yaml_2.3.12        fastmap_1.2.0      lattice_0.22-9     R6_2.6.1          
#> [13] labeling_0.4.3     generics_0.1.4     knitr_1.51         htmlwidgets_1.6.4 
#> [17] pillar_1.11.1      RColorBrewer_1.1-3 tzdb_0.5.0         rlang_1.2.0       
#> [21] stringi_1.8.7      xfun_0.58          fs_2.1.0           S7_0.2.2          
#> [25] otel_0.2.0         timechange_0.4.0   cli_3.6.6          mgcv_1.9-4        
#> [29] withr_3.0.2        magrittr_2.0.5     digest_0.6.39      grid_4.6.0        
#> [33] hms_1.1.4          nlme_3.1-169       lifecycle_1.0.5    vctrs_0.7.3       
#> [37] evaluate_1.0.5     glue_1.8.1         farver_2.1.2       rmarkdown_2.31    
#> [41] tools_4.6.0        pkgconfig_2.0.3    htmltools_0.5.9

16.18 Running Example: The Stickleback Data

NoteRunning example

This section applies the chapter to the course dataset described in Section 1.5 (80 stickleback, 4 treatment groups, 600 genes). The same steps appear on the Week 7 slides, so the book and the lecture can be read side by side.

Everything the course has done with the stickleback data can live in one Quarto document: the prose, the analysis, the figure, and the numbers quoted in the text, all regenerated on every render. A minimal report looks like this:

---
title: "Genotype and microbiota effects on gut gene expression"
author: "Your Name"
format: html
---

```{r}
#| label: setup
#| message: false
library(tidyverse)
stickle <- read_tsv("data/Stickle_RNAseq.tsv", show_col_types = FALSE)
long <- stickle |> pivot_longer(starts_with("Gene"), names_to = "gene", values_to = "count")
```

We measured `r n_distinct(long$gene)` genes in `r nrow(stickle)` fish
(@fig-gene1).

```{r}
#| label: fig-gene1
#| fig-cap: "Gene1 counts by genotype and microbiota."
ggplot(filter(long, gene == "Gene1"), aes(Genotype, count, fill = Microbiota)) + geom_boxplot()
```

The inline code means the sentence “We measured 600 genes in 80 fish” is computed, not typed, so it can never disagree with the data. The chunk label beginning with fig- makes the figure numbered and cross-referenceable. Add format: pdf to the header, once TinyTeX is installed (Section 2.3.5), and the same file becomes a manuscript-ready PDF; add format: revealjs and it becomes slides.

16.19 Summary

Quarto transforms how we communicate scientific work:

  • Markdown provides simple, readable formatting syntax
  • YAML headers configure document settings
  • Code chunks embed executable, reproducible analysis
  • Python chunks run through Jupyter (or reticulate), and Quarto renders .ipynb notebooks directly
  • Callouts, tabsets, and divs structure a document with the same ::: fence syntax
  • Multiple formats serve different audiences from one source
  • Cross-references and citations create professional, navigable documents from @-keys and a .bib file
  • The same toolkit scales up: format: revealjs for talks, scholarly front matter plus a CSL style for journal manuscripts, and website projects for your academic presence on the web

The investment in learning Quarto pays dividends every time you write a report, prepare a presentation, or publish research. Your future self (and your collaborators) will thank you for the reproducibility.

Additional Reading

Exercises

TipPractice Exercises

Exercise 1: First Quarto Document

  1. Create a new file called first_report.qmd
  2. Add a YAML header with title, author, and date
  3. Write a brief introduction using headers, bold, and italic text
  4. Include a bulleted list of your analysis goals
  5. Render to HTML

Exercise 2: Code Integration

  1. Create a document that loads a dataset (use mtcars or similar)
  2. Add a code chunk that calculates summary statistics
  3. Add a code chunk that creates a figure with a caption
  4. Use chunk options to hide code but show results for one chunk
  5. Use chunk options to show code but hide results for another

Exercise 3: Mathematical Notation

  1. Write a document explaining a statistical concept
  2. Include at least one inline equation
  3. Include at least one display equation
  4. Use appropriate callout blocks for tips and warnings

Exercise 4: Multi-Format Output

  1. Configure your document to render to both HTML and PDF
  2. Render both versions with quarto render --to all
  3. Note any differences in how content appears
  4. Adjust settings to optimize for each format

Exercise 5: Tables, Cross-References, and Citations

  1. Type a small pipe table by hand and give it a caption with a {#tbl-...} id
  2. Produce a second table from code (knitr::kable(head(iris, 5)) or pandas) with a tbl- label and tbl-cap
  3. Refer to both tables and to one figure from the text with @
  4. Create a references.bib with two entries, add bibliography: to the YAML, and cite both sources (one in brackets, one in running text)
  5. Render and check that the numbering and reference list are generated automatically

Exercise 6: One Toolkit, Three Outputs

  1. Download the three Week 7 examples from the course Example Files page — the slide deck, the manuscript with its companion files, and the website zip
  2. Render example_slides.qmd, then change the theme: and add one new slide containing an executed code chunk
  3. In the manuscript, add one reference to the .bib file and cite it, add one numbered equation and reference it from the text, and re-render (to PDF with TinyTeX, otherwise to HTML)
  4. Unzip the website, run quarto preview inside the folder, and replace the fictional student’s name, photo, and research blurbs with your own
  5. Keep the personalized site — it becomes your live GitHub Pages site in Week 8 (Section 19.11)

  1. This is the footnote content.↩︎