Quarto as a Project Runbook

Week 8 · Thursday, Nov 12 · Lecture

Dr. Marcela Alfaro Córdoba

Today’s plan

Time What
1:30 What changes in Weeks 8-10
1:35 A README tells you. A runbook does it
1:45 Clone and render the example project
2:05 Anatomy of a Quarto document, read from the runbook
2:35 Break it on purpose
2:55 Your project’s folders, and Tuesday

Learning goals: render a whole project from a fresh clone with one command; read and write the parts of a .qmd (YAML header, chunks, chunk options, inline code, cross-references); explain why a render runs in a fresh session and what that catches.

No AI in today’s exercises. Bring your laptop, charged.

Weeks 8-10: what changes

Important

No more Tuesday-morning sections. The 9:50 slot doesn’t meet in Weeks 8 and 9; in Week 10 it is open time for independent project work. There are still 9 DS, and the two lowest are dropped.

  • Week 8: Quarto for a reproducible project. We work on one example repository, all week
  • Week 9, Thu: recommendations: writing good software, using AI with rules, AI ethics
  • Week 9, Tue Nov 24: peer code review, in class. This is the peer review (5%), done that day. Your repo must be ready to review by 1:30 pm
  • Week 10: project work, presentations, oral Q&A

DS 8 and DS 9 are self-guided on Canvas (PDF only, no check), due Wed Nov 18 and Wed Nov 25. Full credit on DS 1-7? You don’t need to submit them. Missed one or lost points? DS 8 and 9 replace those grades. Participation is still the Ed threads in class.

A runbook

Your project, a month from now

Someone clones your repository:

  • you, after the break
  • me, grading the final report
  • a classmate, on Tue, Nov 24

Can they get from the raw data to your figures without asking you anything?

README vs. runbook

A README… A runbook…
says “run 01-import.R, then 02-clean.R, then…” runs them, in order
can be out of date and nobody notices breaks the render when it is out of date
reports numbers someone typed reports numbers the code computed
is read is read and rendered

A runbook is a Quarto document that runs the whole project, top to bottom, and explains each step. If it renders, the project is reproducible. The README just says “render the runbook”.

Today’s example runbook has a second job: every section teaches the Quarto feature that step needs. You learn Quarto by reading it.

The example project

Question: how did life expectancy, fertility, and CO₂ per person change across world regions, 1952-2007, and how do they relate?

File Source Problem to solve
gapminder.tsv Gapminder Tab-separated; countries by name
wb_fertility_wide.csv World Bank Wide (a column per year), 4 junk lines on top
wb_country_metadata.csv World Bank Mixes countries with “World”, “High income”…
owid_co2_per_capita.csv Our World in Data Countries by code; 11 names spelled differently

Everything from Weeks 3, 6 and 7: reading files, cleaning, pivot_longer(), joins with checked keys. All four are public data, CC BY.

Your turn: clone and render

⏱ 15 min

  1. Clone https://github.com/malfaro2/266-example-analysis and open the folder in Positron (File → Open Folder)
  2. In the R console: renv::restore() and answer y. It installs the exact package versions in renv.lock, for this project only
  3. In the Terminal: quarto render run-analysis.qmd
  4. Open run-analysis.html. What’s in data/processed/ and output/ now that wasn’t there before?

The first render downloads Python and pandas for the Python step (about a minute, needs Wi-Fi). Stuck? Post the first line of the error on the Ed thread “Runbook render”, and help a neighbor.

What just happened

quarto render run-analysis.qmd
  └─ new R session (nothing from your console)
       ├─ R/functions.R
       ├─ R/01-import.R        data/raw/*            (read only)
       ├─ R/02-clean.R         + data/reference/country_name_fixes.csv
       ├─ R/03-reshape-join.R  → data/processed/analysis.csv
       ├─ python/summarize.py  (via reticulate)
       └─ R/04-describe.R      → output/figures/, output/tables/
  └─ run-analysis.html
  • One folder, one job. data/raw/ is never edited; processed/ and output/ are rebuilt every time, so they’re not in git (.gitignore)
  • One script per step, numbered in run order. Shared functions in R/functions.R

Anatomy of a .qmd

1. The YAML header

---
title: "How to run this analysis"
subtitle: "Life expectancy, fertility, and CO₂ by world region, 1952-2007"
date: today
format:
  html:
    toc: true
    number-sections: true
    embed-resources: true     # one self-contained .html file
    code-tools: true          # the </> Code button
execute:
  echo: true                  # defaults for EVERY chunk
  warning: false              # hides warnings AND messages
---
  • Between the two ---: settings for the whole document
  • Two spaces per level, never tabs. A YAML error is the most common first error
  • execute: sets defaults; a chunk can override them

2. Chunks and chunk options

```{r}
#| label: restore
#| eval: false
renv::restore()
```
Option Does Use it for
label: restore names the chunk finding where a render failed
eval: false shows the code, doesn’t run it one-time setup the reader runs
echo: false runs it, shows output only a figure in a report for non-coders
include: false runs it, shows nothing loading packages quietly
message: false hides messages noisy library() calls

Find one chunk of each kind in the runbook. Which option does the setup chunk use, and why does the restore chunk need eval: false?

3. Inline code

In the source:

The final analysis table has `r nrow(analysis)` rows,
`r length(unique(analysis$country))` countries, and covers
`r min(analysis$year)` to `r max(analysis$year)`.

In the HTML:

The final analysis table has 1361 rows, 139 countries, and covers 1962 to 2007.

Every number in a sentence comes from code.

If the data change, the sentence changes. If you type “142 countries” by hand, it stays wrong forever. (Keep this sentence in mind for Week 9. Does it agree with the subtitle?)

4. Tables, figures, cross-references

```{r}
#| label: fig-scatter
#| fig-cap: "Fertility and life expectancy in 2007."
#| fig-width: 8
#| fig-height: 5
fig_scatter
```

@fig-scatter shows a strong negative relationship...
  • Label starts with fig- + a fig-cap → numbered Figure 1, and @fig-scatter becomes a link
  • tbl- + tbl-cap for tables (knitr::kable() makes a clean one)
  • {#sec-python} after a heading → @sec-python links to that section

5. Callouts

::: {.callout-warning}
## A step that stops the render on purpose

If a country name ever fails to match, the render **stops with an error**
instead of quietly dropping that country.
:::
  • callout-note, -tip, -warning, -important, -caution
  • In a runbook: warnings about one-time setup, decisions a reader must know about

These slides are Quarto too (format: revealjs). Same chunks, same callouts, different output.

6. A render is a fresh session

Rendering starts a new R session and runs every chunk top to bottom.

  • Nothing from your console exists there: no object you made by hand, no package you loaded interactively
  • So a document that renders proves the code is complete
  • And a document that only works after you “run that one line first” is not reproducible

Break it on purpose

Your turn: three ways to break a runbook

⏱ 15 min

In pairs. For each one: predict what happens, render, then read the error. Which chunk label does it name?

  1. Absolute path. In R/01-import.R, change "data/raw/gapminder.tsv" to the full path on your laptop. Does it render? Would it render on your partner’s laptop?
  2. Hidden state. In the console run latest <- 2007. In the runbook, add a chunk that uses latest. Render.
  3. A missing fix. Delete the "Korea, Rep." line from data/reference/country_name_fixes.csv. Render.

When you’re done: git restore . puts everything back.

What we found

Break Result Lesson
Absolute path Renders on your laptop only The worst kind of bug: invisible to you. Paths are relative to the project folder (execute-dir: project in _quarto.yml)
Hidden state object 'latest' not found, in your chunk The console is not the document. If the analysis needs it, a chunk makes it
Missing fix Stops at stopifnot(!any(is.na(gapminder$iso3))) in chunk clean A render that fails loudly beats a report that is quietly wrong

Without that stopifnot(), South Korea just disappears: no error, one fewer point in Figure 1, and nobody notices. Ed thread “Break it”: which break surprised your pair most?

Your project

Map your project onto this structure

⏱ 8 min

On paper or in a text file, sketch your project’s folder tree:

  1. Which of your files are raw data? Are any edited by hand? (They shouldn’t be)
  2. What are your pipeline steps? One script each, numbered
  3. Which outputs are rebuilt (and so go in .gitignore)?
  4. Is there any path in your code that starts with /Users/ or C:\?

On Tuesday you start your own run-analysis.qmd from a template. Reorganize your folders before Tuesday so the workshop time goes to the runbook.

Key points

  • A runbook runs the project; a README only describes it. If it renders from a fresh clone, the project is reproducible
  • One folder, one job: data/raw/ read-only; processed/ and output/ rebuilt and not in git
  • YAML header = settings for the whole document; execute: = defaults for every chunk
  • Chunk options with #|: label, eval, echo, include, fig-cap
  • Inline code for every number in a sentence
  • fig-/tbl- labels + captions → numbered, cross-referenced with @
  • A render is a fresh session: hidden state and absolute paths break it, so they get found
  • stopifnot() makes the render fail loudly when an assumption breaks

Before Tuesday

Tuesday, Nov 17 (lecture only, no DS section; DS 8 is on Canvas): R and Python in one document, renv, and a workshop where you start your own runbook.