Skip to main content

12  Lab Reports with Quarto

The usual way to write a lab report is to do the analysis in one program, then copy numbers and paste figures into another. Every copy is a chance for the report to disagree with the analysis.

Quarto removes the copying. One file, ending in .qmd, holds the prose, the equations, and the code. When you render it, Quarto runs the code from top to bottom and builds a finished document with the figures, tables, and numbers the code produced. Change the data, render again, and everything updates. This book is written that way.

Quarto comes with RStudio, so there is nothing new to install.

12.1 A first document

In your lab’s project (Chapter 1), choose File, then New File, then Quarto Document. Give it a title, leave the format as HTML, and click Create. Save the file in the project folder as, say, pendulum-report.qmd.

RStudio can show the file in two ways, switched with the Source and Visual buttons at the top left of the editor. Visual looks like a word processor. Source shows the plain text that is really in the file, and this chapter uses it.

A .qmd file has three ingredients.

The YAML header sits at the very top between two lines of three dashes. It holds settings for the whole document: title, author, date, and format.

Markdown text is everything else that is not code. It is plain text with light markup:

You type You get
## Method a section heading (# is one level up, ### one down)
**bold** and *italic* bold and italic
- item at the start of a line a bulleted list item
1. item at the start of a line a numbered list item
[CODATA](https://physics.nist.gov/cuu/Constants/) a link

Leave a blank line between paragraphs, and before and after a list.

Code chunks are blocks of R that start with a line ```{r} and end with a line of three backticks. Insert one with Ctrl+Alt+I (Cmd+Option+I on a Mac). The green arrow at the top right of a chunk runs it on the spot.

12.2 A complete report

Here is a short but complete pendulum report. The R in it is all familiar: pendulum_summary from Chapter 7, the linearized plot from Chapter 8, and the straight-line fit from Chapter 9.

---
title: "Measuring g with a Simple Pendulum"
author: "Your Name"
date: 2026-10-14
format: html
---

```{r}
#| label: setup
#| include: false
library(tidyverse)
library(broom)
```

## Theory

For small swings, a pendulum of length $L$ has period $T = 2\pi\sqrt{L/g}$.
Squaring both sides gives a straight line in $L$:

$$
T^2 = \frac{4\pi^2}{g} L
$$

so the slope of $T^2$ against $L$ is $4\pi^2/g$.

## Data

We timed ten full swings, three times, at each of nine lengths.
@tbl-periods gives the mean period at each length.

```{r}
#| label: tbl-periods
#| tbl-cap: "Mean period at each length, with its standard error."
#| echo: false
pendulum_summary <- read_csv("data/pendulum.csv", show_col_types = FALSE) |>
  mutate(period_s = time_10_s / 10) |>
  summarise(
    period_se = sd(period_s) / sqrt(n()),
    period_s  = mean(period_s),
    .by = length_m
  ) |>
  select(length_m, period_s, period_se)

knitr::kable(
  pendulum_summary,
  digits = c(1, 3, 3),
  col.names = c("Length (m)", "Period (s)", "Standard error (s)")
)
```

## Results

```{r}
#| label: fit
#| echo: false
fit <- lm(period_s^2 ~ length_m, data = pendulum_summary)
slope    <- tidy(fit)$estimate[2]
slope_se <- tidy(fit)$std.error[2]
g    <- 4 * pi^2 / slope
g_se <- g * slope_se / slope
```

@fig-fit shows $T^2$ against $L$ with the best-fit line. Its slope is
`r round(slope, 3)` s²/m, which gives
$g =$ `r round(g, 2)` $\pm$ `r round(g_se, 2)` m/s².

```{r}
#| label: fig-fit
#| fig-cap: "Period squared against length. The line is a least-squares fit."
#| echo: false
ggplot(pendulum_summary, aes(x = length_m, y = period_s^2)) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, color = "gray50") +
  geom_point() +
  labs(x = "Length (m)", y = "Period squared (s²)")
```

The sections below take it apart.

12.3 Chunk options

Lines at the top of a chunk that start with #| are options. They control how the chunk appears in the report, not what the code does. The ones you will use most:

  • label: fit names the chunk, which makes a failed render easier to track down.
  • echo: false runs the code and shows its output but hides the code itself. A lab report wants the figure, not the ggplot2 call that made it.
  • include: false runs the code and shows nothing at all. It suits the chunk that loads packages.
  • warning: false and message: false hide warnings and the chatter some functions print.
  • fig-cap: "..." and tbl-cap: "..." give a figure or a table its caption.

12.4 Numbers in sentences

The Results paragraph of the report never types the value of \(g\). It contains a backtick, the letter r, a space, an R expression, and a closing backtick:

which gives $g =$ `r round(g, 2)` m/s².

When the document is rendered, that inline code is replaced by the value of the expression, so the sentence reads “which gives \(g =\) 9.84 m/s²”, the value found in Chapter 9. Correct one stopwatch reading in the CSV file, and the table, the fit, the figure, and this sentence all change together on the next render.

12.5 Equations

Quarto typesets mathematics written in LaTeX notation, which physicists also use for papers. Put it between single dollar signs to set it inside a sentence, and between double dollar signs to display it on a line of its own. The source $T = 2\pi\sqrt{L/g}$ produces \(T = 2\pi\sqrt{L/g}\), and

$$
T^2 = \frac{4\pi^2}{g} L
$$

produces

\[ T^2 = \frac{4\pi^2}{g} L \]

A small vocabulary covers most of a first-year course: ^ and _ for superscripts and subscripts (with braces around anything longer than one character, as in v_{max}), \frac{a}{b} for fractions, \sqrt{x}, Greek letters by name (\theta, \omega, \Delta), and \pm.

12.6 Figures, tables, and cross-references

Give a plotting chunk a label that starts with fig- and a fig-cap, and the figure gets a number and a caption. You can then refer to it from the text: writing @fig-fit produces “Figure 1”, and the numbering stays correct when you add another figure above it. Tables work the same way with labels that start with tbl-, the tbl-cap option, and @tbl-periods in the text.

A tibble printed in a report looks like Console output. kable(), from the knitr package, turns a data frame into a properly formatted table. Its digits argument rounds each column and col.names supplies headings with units. The report calls it as knitr::kable(), with the double colon from Chapter 6, so knitr does not need loading. This is the table it makes:

library(tidyverse)

pendulum_summary <- read_csv("data/pendulum.csv", show_col_types = FALSE) |>
  mutate(period_s = time_10_s / 10) |>
  summarise(
    period_se = sd(period_s) / sqrt(n()),
    period_s  = mean(period_s),
    .by = length_m
  ) |>
  select(length_m, period_s, period_se)

knitr::kable(
  pendulum_summary,
  digits = c(1, 3, 3),
  col.names = c("Length (m)", "Period (s)", "Standard error (s)")
)
Length (m) Period (s) Standard error (s)
0.2 0.897 0.001
0.3 1.099 0.004
0.4 1.270 0.003
0.5 1.417 0.002
0.6 1.554 0.002
0.7 1.678 0.001
0.8 1.794 0.001
0.9 1.899 0.002
1.0 2.005 0.002

knitr is the package that runs the chunks. It arrived when you installed the tidyverse.

12.7 Rendering

Click the Render button above the editor, or press Ctrl+Shift+K (Cmd+Shift+K on a Mac). Quarto starts a fresh R session, runs every chunk in order, and writes pendulum-report.html next to the .qmd file. That file is the report: it opens in any browser and can be uploaded or emailed as it is.

NotePDF output

If your course wants a PDF, change the header line to format: pdf. Quarto makes PDFs with LaTeX, which is a separate install. The smallest one is TinyTeX: click the Terminal tab next to the Console, type quarto install tinytex, and press Enter. You do this once.

12.8 Good habits

  • One project per lab, with relative paths, as in Chapter 1. The report then renders on your lab partner’s computer as well as yours.
  • Raw data is read-only. Keep the files you recorded in data/ and never edit them by hand or overwrite them from code. Corrections and exclusions belong in the code, where your marker can see them.
  • Render from scratch before handing in. Choose Session, then Restart R, and render. If that succeeds, the report stands on its own.
WarningA render does not see your Environment

The most common render error is object 'pendulum' not found from code that runs perfectly in the Console. The object exists in your interactive session but no chunk in the document creates it. Packages are the same: the document needs its own library() calls.

A rendered report is the end of the workflow this book has been building: read the data, transform it, plot it, fit it, write it up. Chapter 13 points to where each of those threads continues.