Every Number Comes from Code

Reproducible documents with Quarto

Brendan Chapuis

April 14, 2027

Draws on slides by Matthew DeHaven and talks by Scott Cunningham
Course Home Page

Lecture Goals

  • Why every number in your paper should come from code
  • Quarto: one file with text and code, rendered to a document
    • The YAML header, Markdown, and code cells
    • Inline code: numbers in sentences, computed in code
    • Tables and figures from code, with captions and cross-references
    • Output formats, projects, and freezing
  • Quarto slides, and some advice for your talk
  • What this means for your final project

The Pipeline Is the Ground Truth

Where We Are

  • Agents can now write your code, run it, and make your tables.
  • On 4/5 you wrote down rules for them; on 4/7 you reviewed their pull requests.
  • The last link is the paper itself.
    • Who typed the numbers in it?
    • Do they still match the code that made them?

Today: a document where no number is typed by hand.

The Pipeline Is the Ground Truth

Every table and figure in the paper is produced by code that can be re-run from the raw data.

  • Nothing in the paper is made by hand or remembered. It is regenerated.
  • Every figure traces back to the script that made it.
  • “Is this number stale?” has an answer: re-run and see.

If it is not produced by the pipeline, it is not evidence.

Adapted from Scott Cunningham’s Baylor talk (2026).

How Hand-Typed Numbers Go Wrong

The usual way: run the regression, read the coefficient, type it into the paper.

  • You re-clean the data. The table updates; the sentence on page 12 does not.
  • You copy 0.0428 as 0.428.
  • The abstract, the text, and the table disagree, and nobody knows which is current.

None of these is a coding error. The code is fine. The document is wrong.

Why This Matters More With Agents

  • An agent writes prose as easily as code.
  • It can write “the effect is 0.42” in a paragraph without running anything.
  • The sentence looks exactly like one backed by a regression.

A number computed in the document has provenance: you can point to the line that made it.

A typed number has none, whoever typed it.

What Quarto Is

Quarto

Quarto is an open-source publishing system.

  1. You write one file (.qmd) with text and code.
  2. Quarto runs the code and renders the file to a document.
  • Outputs: HTML, PDF, Word, slides, websites, books.
  • Languages: R, Python, Julia.
  • These slides, the syllabus, and the course website are all Quarto.

Where the Name Comes From

A quarto is a book made by folding a sheet twice: one source, many pages.

How Quarto Renders

  • knitr (for R) or Jupyter (for Python) runs the code and writes Markdown.
  • Pandoc turns the Markdown into HTML, PDF, Word, …

Quarto and R Markdown

You may have seen R Markdown (.Rmd) files.

  • Quarto is its successor, from the same team (Posit).
  • Works with several languages, not only R.
  • One syntax for every output format.

Most .Rmd files render in Quarto with few changes.

A Quarto Document

Two Pieces

Every .qmd file has:

  1. A header in YAML, between two --- lines: settings for this document.
  2. A body in Markdown: the text, with code cells mixed in.
paper.qmd
---
title: "Life Expectancy and Income"
author: "Your Name"
format: html
---

## Introduction

Some text with **bold** and a [link](https://quarto.org).

YAML Syntax

YAML sets options with key: value. Indentation means nesting.

title: "Life Expectancy and Income"
format:
  html:
    toc: true
  pdf:
    documentclass: article
execute:
  echo: false
  • Indent with spaces, never tabs. Two spaces is the convention.
  • A wrong indent changes the meaning, often silently.

Markdown Body

The body is the Markdown you already know from READMEs.

## A Section Header

Plain text, *italics*, **bold**, and `code`.

- A bullet
- Another bullet

1. A numbered item

[A link](https://quarto.org) and an image: ![](figs/plot.png)

Math

Math uses LaTeX syntax.

  • Inline between single dollar signs: $\beta_1$ gives \(\beta_1\).
  • Display math between double dollar signs:
$$
y_{it} = \beta \log(\text{gdp}_{it}) + \gamma_t + \varepsilon_{it}
$$

\[ y_{it} = \beta \log(\text{gdp}_{it}) + \gamma_t + \varepsilon_{it} \]

Code Cells

A Code Block Is Not a Code Cell

Three backticks make a code block: it is shown, not run.

```
x <- 2 + 2
```

Add {r} and it becomes a code cell: Quarto runs it and shows the output.

```{r}
x <- 2 + 2
x
```
[1] 4

A Document With a Code Cell

paper.qmd
---
title: "Life Expectancy and Income"
format: html
---

## Data

```{r}
library(gapminder)
nrow(gapminder)
```

Some more text.

When you render, the cell runs and its output appears in the document.

Engines

Quarto runs code with an engine.

  • Cells with {r}: the knitr engine.
  • Cells with {python} (and no R cells): the Jupyter engine.
  • {julia} cells: Julia’s own engine.

One engine per document.

  • With knitr, Python cells still run, through the reticulate package.
  • Usually simpler: one language per document, and scripts in other languages write files the document reads.

Cell Options

Options go at the top of a cell, on lines starting with #|.

```{r}
#| label: fig-income
#| echo: false
#| fig-cap: "Life expectancy and income"
ggplot(gapminder, aes(log(gdpPercap), lifeExp)) + geom_point()
```

The most common:

Option What it does
echo show the code?
eval run the code?
output show the result?
include show anything at all? (it still runs)
warning, message show warnings and messages?

echo: false: Show the Result, Not the Code

Source

```{r}
#| echo: false
2 + 2
```

Rendered

[1] 4
```{r}
#| echo: true
2 + 2
```
2 + 2
[1] 4

In a paper you usually want echo: false: readers see results, and the code lives in the repository.

output and include

Source

```{r}
#| output: false
2 + 2
```
```{r}
#| include: false
2 + 2
```

Rendered

2 + 2

(The second cell ran, but shows nothing.)

A Setup Cell

Most documents start with a hidden cell that loads packages and data.

```{r}
#| label: setup
#| include: false
library(fixest)
library(ggplot2)
gap <- read.csv("data/clean/gapminder.csv")
```
  • It runs, so everything below can use gap.
  • Package startup messages stay out of your paper.

Options for the Whole Document

Set an option once in the YAML instead of in every cell:

paper.qmd
---
title: "Life Expectancy and Income"
format: html
execute:
  echo: false
  warning: false
---
  • A cell option still overrides it: #| echo: true shows that one cell.

Cells Share One Session, Top to Bottom

All cells run in order, in one fresh R session.

paper.qmd
```{r}
y <- 2 + 2
```

Some text.

```{r}
y * 10
```
y <- 2 + 2

Some text.

y * 10
[1] 40

Fresh means fresh: objects in your console do not exist when you render. If the document renders, the code runs from scratch. That is a check.

Inline Code

Numbers Inside Sentences

Inline code puts a computed value in the middle of a sentence: `{r} expression`.

paper.qmd
```{r}
#| echo: false
n_countries <- length(unique(gapminder$country))
```

The panel covers `{r} n_countries` countries.

The panel covers 142 countries.

Change the sample, re-render, and the sentence changes with it.

A Coefficient in a Sentence: The Code

In a hidden cell, run the regression and pull out the pieces:

m <- feols(lifeExp ~ log(gdpPercap) | year,
           cluster = ~country, data = gapminder)

b  <- coef(m)["log(gdpPercap)"]
se <- se(m)["log(gdpPercap)"]
n  <- nobs(m)
  • coef(), se(), and nobs() work on any fixest model.
  • broom::tidy(m) gives the same numbers as a data frame.

A Coefficient in a Sentence: The Text

paper.qmd
A one-log-point increase in GDP per capita is associated with
`{{r}} round(b, 2)` more years of life expectancy
(SE `{r} round(se, 2)`, N = `{r} format(n, big.mark = ",")`).

Renders as:

A one-log-point increase in GDP per capita is associated with 7.77 more years of life expectancy (SE 0.38, N = 1,704).

Every number in that sentence traces to the cell on the previous slide.

Formatting Numbers

Do the formatting in R, once, with a small helper:

fmt <- function(x, digits = 2) formatC(x, format = "f", digits = digits)

fmt(b)
log(gdpPercap) 
        "7.77" 
fmt(0.5, digits = 3)
[1] "0.500"
scales::percent(0.0428, accuracy = 0.1)
[1] "4.3%"
format(1234567, big.mark = ",")
[1] "1,234,567"
  • round(0.5, 2) prints 0.5; fmt() keeps the trailing zero.
  • Put helpers like fmt() in your setup cell or a sourced script.

What Counts as “a Number”

All of these should come from code:

  • Coefficients, standard errors, p-values
  • Sample sizes, number of states, number of years
  • The sample period (“from 1952 to 2007”)
  • Means and percentages in the data description
  • “Twice as large as”: compute the ratio

Numbers that are not results can be typed: the year a law passed, an equation number, a citation.

Spot the Typed Numbers

We use a panel of 142 countries observed every five years from 1952 to 2007. A one-log-point increase in GDP per capita is associated with 7.8 more years of life expectancy, about 13% of the sample mean.

  • 142, 1952, 2007: from the data. Inline code.
  • 7.8: a coefficient. Inline code.
  • 13%: a ratio of two computed numbers. Inline code.
  • “every five years”: a fact about the data. Compute it, or check it in code.

Tables and Figures From Code

Regression Tables: etable and modelsummary

You know etable() from 2/24. It prints well in the console:

m2 <- feols(lifeExp ~ log(gdpPercap) | country + year,
            cluster = ~country, data = gapminder)
etable(m, m2, keep = "gdp")
                                m              m2
Dependent Var.:           lifeExp         lifeExp
                                                 
log(gdpPercap)  7.768*** (0.3772) 1.450* (0.6795)
Fixed-Effects:  ----------------- ---------------
year                          Yes             Yes
country                        No             Yes
_______________ _________________ _______________
S.E.: Clustered       by: country     by: country
Observations                1,704           1,704
R2                        0.71952         0.93600
Within R2                 0.65153         0.01859
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

For documents, modelsummary() makes a table in the output format: HTML, LaTeX, or Word.

A Table in the Document

modelsummary(list("Year FE" = m, "Country and year FE" = m2),
             coef_map = c("log(gdpPercap)" = "Log GDP per capita"),
             gof_map = c("nobs", "r.squared"), stars = TRUE)
Table 1: Life expectancy and log GDP per capita
Year FE Country and year FE
+ p < 0.1, * p < 0.05, ** p < 0.01, *** p < 0.001
Log GDP per capita 7.768*** 1.450*
(0.377) (0.679)
Num.Obs. 1704 1704
R2 0.720 0.936

Captions and Cross-References

Give a cell a label with a prefix, and a caption:

```{r}
#| label: tbl-main
#| tbl-cap: "Life expectancy and log GDP per capita"
modelsummary(list("Year FE" = m, "Country and year FE" = m2))
```

Then refer to it in the text with @:

@tbl-main shows that the association shrinks with country fixed effects.
  • Prefixes: tbl- for tables, fig- for figures, eq- for equations, sec- for sections.
  • Quarto numbers them and writes “Table 1”, even after you reorder.

A Figure From Code

gapminder |>
  subset(year == 2007) |>
  ggplot(aes(gdpPercap, lifeExp)) +
  geom_point(alpha = 0.6) +
  scale_x_log10(labels = scales::dollar) +
  labs(x = "GDP per capita (log scale)",
       y = "Life expectancy") +
  theme_minimal(base_size = 16)
Figure 1: Life expectancy and income, 2007

Referring to the Figure

paper.qmd
@fig-income plots life expectancy against income in 2007.

Renders as:

Figure 1 plots life expectancy against income in 2007.

  • fig-width and fig-height (in inches) set the size.
  • fig-cap is the caption; the fig- label makes it numbered.
  • Never paste a screenshot of a plot. Re-render instead.

Two Ways to Organize the Pipeline

A. Compute in the document. Small projects: the .qmd loads clean data and runs the models.

B. Scripts compute, the document reads. Bigger projects, and most of yours:

code/01-clean.R       data/raw/   ->  data/clean/
code/02-estimate.R    data/clean/ ->  output/models.rds
paper.qmd             output/     ->  paper.pdf
  • Slow estimation runs once, in a script.
  • The paper still never contains a typed number: it reads the saved results.

Pattern B in the Document

paper.qmd
```{r}
#| include: false
models <- readRDS("output/models.rds")
b <- coef(models$main)["log(gdpPercap)"]
```

The coefficient on log GDP per capita is `{r} fmt(b)`.
  • Save model objects or small tables with saveRDS() or write.csv().
  • One script (main.R, or a Makefile) runs every step, then renders the paper.
  • “Is this output stale?” Re-run the whole thing and compare.

Output Formats

Change One Line

The same file renders to different formats. Only format: changes.

format: html     # a web page
format: pdf      # through LaTeX
format: docx     # Microsoft Word
format: typst    # a PDF through Typst

Or several at once:

format:
  pdf: default
  docx: default

PDF, Word, and Typst

  • PDF (pdf): Quarto writes LaTeX and compiles it. Needs a LaTeX installation: run quarto install tinytex once.
  • Word (docx): for coauthors who track changes in Word. Tables from modelsummary come out as Word tables.
  • Typst (typst): a newer typesetting system, built into Quarto. Compiles much faster than LaTeX; fewer journal templates.

For your final project, PDF or Typst is the natural choice.

Citations

Keep your references in a BibTeX file and cite them by key.

paper.qmd
---
bibliography: references.bib
---
As in @acemoglu2001, we use ... [see also @card1994, p. 774].
  • Quarto formats the citations and adds a reference list at the end.
  • Google Scholar, Zotero, and most journals export BibTeX.
  • Check every entry an agent adds: invented references look like real ones.

Projects

Quarto Projects

A folder with a _quarto.yml file is a Quarto project.

  • Settings in _quarto.yml apply to every document in the folder.
  • quarto render with no file name renders the whole project.
Terminal
quarto create project      # pick: default, website, manuscript, book

_quarto.yml

_quarto.yml
project:
  output-dir: _output
  execute-dir: project

format:
  pdf:
    documentclass: article
    number-sections: true

execute:
  echo: false
  warning: false
  • A document’s own YAML overrides the project settings.

execute-dir: project

Where does code look for files?

  • Default: relative to the document’s folder.
  • With execute-dir: project: relative to the project root.
read.csv("data/clean/gapminder.csv")   # works from any .qmd in the project

This course website uses execute-dir: project. It keeps paths in the paper the same as paths in your scripts.

Websites Are Projects Too

You built a personal website on 3/24. If you used Quarto, it was a project like this:

_quarto.yml
project:
  type: website
  output-dir: docs
website:
  navbar:
    left: [index.qmd, research.qmd]
  • Same .qmd files, rendered to linked HTML pages.
  • A project website is a good home for your final project’s paper and slides.

Freeze and Cache

Rendering re-runs every cell. When that is slow:

  • execute: freeze: auto in _quarto.yml: a project-wide render only re-runs documents whose source changed.
  • #| cache: true on a cell: knitr saves that cell’s result and re-runs it when its code changes.

Both look only at your code, not at your data.

  • Change a data file, and a frozen or cached result can be stale.
  • Before you submit, render from scratch: quarto render --cache-refresh, or delete _freeze/ and the _cache folders.

Quarto Slides

Slides Are Documents Too

Your presentation can be Quarto, from the same project as your paper.

  • format: revealjs: HTML slides (these slides).
  • format: beamer: PDF slides through LaTeX.

The figures in your talk then come from the same code as the figures in your paper.

Slide Syntax

Each ## header starts a new slide.

talk.qmd
---
title: "Life Expectancy and Income"
author: "Your Name"
format: revealjs
---

## The Question

Does income buy years of life?

## The Answer

```{r}
#| echo: false
etable(m, m2, keep = "gdp")
```

Pauses and Incremental Lists

## A Slide

First point.

. . .

Shown after a click.

::: {.incremental}
- one bullet at a time
- like this
:::

First point.

Shown after a click.

  • one bullet at a time
  • like this

Columns

:::: {.columns}
::: {.column width="40%"}
Text on the left.
:::
::: {.column width="60%"}
```{r}
#| echo: false
ggplot(gapminder, aes(log(gdpPercap), lifeExp)) + geom_point()
```
:::
::::
  • Four colons for the outer columns div, three for each column.
  • Text left, figure right is the most useful slide layout in a talk.

Code Output on Slides

In a talk, show results, not code: set echo: false in the YAML.

Showing code is occasionally the point. Then put the output beside it:

gapminder |>
  subset(year == 2007) |>
  ggplot(aes(gdpPercap, lifeExp)) +
  geom_point() +
  scale_x_log10()

Sharing Slides

  • revealjs slides are an HTML file plus a folder of supporting files.
  • embed-resources: true packs everything into one file you can email or upload.
format:
  revealjs:
    embed-resources: true
  • To get a PDF: open the slides in a browser, press E, then print to PDF.

Presentation Advice

Your Talk

  • Presentations are 4/26 and 4/28: [TBD: talk length and slide count].
  • Tell us:
    • your question,
    • how you answer it (data and method),
    • what you found so far, with at least one figure.
  • Two slides of introduction, at most.
    • First: the question and why it matters.
    • Second: the answer, or a preview of it.

Slides

  • Less text. Short lines, not paragraphs. You say the rest.
  • Introduce every figure. The x-axis, the y-axis, each line, then the takeaway.
  • Color for emphasis, not decoration. One highlighted phrase draws the eye.
  • Pace. About one slide per two minutes. Faster means the audience is not following.

Colors Everyone Can Read

About 1 in 12 men has some form of color blindness, and projectors wash colors out.

  • Avoid red against green, and rainbow palettes.
  • Use a palette built for this: viridis (in ggplot2 as scale_color_viridis_d()).
  • Check: does the figure still work in grayscale?

Practice Out Loud

  • Practice means speaking out loud, not reading the slides to yourself.
  • Know what you will say on every slide, and be able to start from any one.
  • Record yourself once. You will find the slides that do not work.
  • Speak from your diaphragm, slowly and clearly, to the back of the room.

Your Final Project

The Requirement

Your final project paper is a Quarto document, and every number in it comes from code.

  • Every number in the text is inline code.
  • Every table and figure is made by a code cell, or read from a file your code saved.
  • quarto render on a fresh clone rebuilds the paper.

Your slides can be Quarto too, from the same code.

What the Repository Looks Like

my-project/
├── AGENTS.md          # rules for agents (from 4/5)
├── README.md          # how to rebuild everything
├── renv.lock
├── _quarto.yml
├── data/raw/          # never edited
├── code/              # clean, estimate, save
├── output/            # saved models, tables, figures
├── paper.qmd
└── slides.qmd

Directing Agents to Work This Way

Write it down, as on 4/5. For example, in AGENTS.md:

AGENTS.md
- Never type a result into paper.qmd. Every number in the text
  is inline R code that reads from output/.
- Tables and figures are made by code cells or by scripts in code/.
- After any change to code/ or data/, run main.R, then
  quarto render paper.qmd, and report any change in a number.

Then check, as on 4/7: in the diff, does any new number appear in the prose without {r}?

A Crude Check for Typed Numbers

Search the prose for decimals:

Terminal
grep -nE '[0-9]+\.[0-9]+' paper.qmd
  • Read every line it finds.
  • A match inside `{r} ...` or a code cell is fine.
  • A match in plain text is a typed number. Replace it, or justify it.

On 4/19 we go further: tests, and the same estimate computed in R and in Python.

Before You Submit

  1. Clone your repository into a new folder.
  2. Restore packages: renv::restore().
  3. Run the pipeline, then quarto render paper.qmd.
  4. Does the paper match the one you are about to submit?

Before presentations, an agent (or a classmate) has to do exactly this from your repository alone.

Paper due date: [TBD: final paper due date].

Summary

  • The pipeline is the ground truth. If a number is not produced by code, it is not evidence.
  • A .qmd file is a YAML header plus Markdown plus code cells.
  • Cell options (echo, include, label, fig-cap) control what the reader sees.
  • Inline code puts computed numbers in sentences.
  • modelsummary and ggplot2 make tables and figures; @tbl- and @fig- refer to them.
  • Same file, many formats: HTML, PDF, Word, Typst, slides.
  • Render from scratch before you trust the output.

Next Time

  • 4/19, checking results: tests, R and Python agreeing on the same estimate, and a second agent as auditor.
  • 4/21, research design with agents: design before outcomes, and an in-class experiment on what steers agents.

Quarto documentation: quarto.org/docs/guide