Lesson 16 of 17 · Week 08 · Thu Nov 12 · Tue Nov 17

Reports with Quarto

Questions

Objectives

Code and prose in one document

A Quarto document (.qmd) mixes three things: a YAML header with settings, Markdown prose, and code cells that run when you render the document. Rendering runs all the code from top to bottom in a fresh R session and weaves the results (numbers, tables, figures) into an HTML, PDF or Word file. Change the data, re-render, and every number and figure updates. That's what makes a report reproducible.

---
title: "Life expectancy and income"
author: "Your Name"
format: html
---

## Introduction

We look at *how* life expectancy relates to income in **22 countries**.

```{r}
#| label: load
library(ggplot2)
gm <- read.csv("data/gm_excerpt.csv")
```

The data have `{r} nrow(gm)` rows.

Quarto is the successor to R Markdown. It works with R, Python and more, and is built into Positron.

Adapted from Software Carpentry's “Producing Reports With knitr” episode (CC BY 4.0, The Carpentries). Text, examples and exercises have been rewritten for this course.

The YAML header

The header sits between two lines of three dashes, at the very top. It's key: value pairs, and indentation matters (use spaces, not tabs):

---
title: "Week 08 report"
author: "Ana Rojas"
date: today
format:
  html:
    toc: true            # table of contents
    code-fold: true      # code hidden behind a "Code" button
execute:
  echo: false            # applies to every cell unless a cell says otherwise
  warning: false
---

For a PDF, use format: pdf (needs a LaTeX installation: run quarto install tinytex once in the terminal) and for Word, format: docx.

Markdown in 60 seconds

## A section heading        (# for the title level, ### for a subsection)

Plain text. *Italic*, **bold**, `code`, and a [link](https://quarto.org).

- a bulleted list
- with two items

1. a numbered list
2. also works

Leave a blank line before headings, lists and code cells, or Markdown may not recognise them.

Code cells and cell options

A code cell starts with ```{r} on its own line and ends with ```. Options go at the top of the cell, on lines starting with #|:

```{r}
#| label: fig-lifeexp
#| fig-cap: "Life expectancy rises with income."
#| fig-width: 7
#| fig-height: 4
#| echo: false
ggplot(gm, aes(gdpPercap, lifeExp)) + geom_point() + scale_x_log10()
```
OptionEffect
echo: falsehide the code, show the output
eval: falseshow the code, don't run it
include: falserun it, but show neither code nor output (e.g. loading packages)
warning: false, message: falsehide warnings / messages
label: fig-name + fig-capa numbered figure you can refer to with @fig-name
fig-width, fig-heightfigure size in inches

Labels must be unique within the document. A label starting with fig- makes a cross-referenceable figure.

Inline code

To put a computed number in a sentence, use inline code: `{r} expression`. For example, The mean life expectancy was `{r} round(mean(gm$lifeExp), 1)` years. renders as a sentence with the number filled in. Never type numbers from your output into the text by hand. If the data changes, they'd be wrong.

Rendering in Positron (Tuesday task)

The exercises below check the syntax of your document; the browser can't render Quarto. For Tuesday, render a real report on your computer:

  1. In your course folder, create reports/week08.qmd (File → New File… → Quarto Document).
  2. Build it from your exercise answers: a YAML header, an introduction, a cell that loads packages (include: false), a cell that reads data with a relative path, a labelled figure with a caption, and one sentence with inline code.
  3. Click Preview at the top of the editor (or open the Command Palette with Ctrl/Cmd+Shift+P and run Quarto: Preview). Positron comes with its own copy of Quarto, so there's nothing extra to install. The rendered page opens in the Viewer, and week08.html appears next to the .qmd.
  4. If it fails, read the error. It names the cell label and line. Remember that rendering starts a fresh R session, so everything the document needs must be created inside it.

Bring to class: your .qmd and the rendered .html.

Exercises

Each exercise gives you up to 10 checked attempts. Use Run as many times as you like to experiment first, then click Check answer when you're ready. Your exercises use numbers/subsets unique to you, so answers won't match a classmate's exactly.

Exercise 1 — Markdown only

0 / 10 attempts used

Your document is written inside an R raw string, r"---( … )---". Type the file's content between the parentheses exactly as it would appear in a .qmd. Write a document with:

  • a YAML header with a title and format: html;
  • at least two ## section headings;
  • some italic text (with single *s) and a bulleted list of at least two items;
  • no code cells.
Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 2 — Add code cells

0 / 10 attempts used

Write a document (YAML header with title and format: html) with three R code cells:

  1. one that loads ggplot2;
  2. one that reads data/gm_excerpt.csv into gm with read.csv() and a relative path;
  3. one that makes a plot with ggplot().

Put a sentence of prose before each cell saying what it does.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 3 — Cell options for a figure

0 / 10 attempts used

Write one R code cell (no YAML needed this time) that draws a ggplot and uses cell options to:

  • hide the code but keep the plot;
  • make the figure w inches wide and h inches tall (click Run for your values);
  • give it a label that makes it a cross-referenceable figure, and a caption.
Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 4 — Inline code

0 / 10 attempts used

Write a paragraph (no YAML or cells needed) with two sentences that use inline R code (`{r} ...`) to report numbers from gm: the number of countries (nlevels(gm$country) or similar), and the mean life expectancy rounded to 1 decimal. No typed-in numbers!

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Exercise 5 — A header with settings

0 / 10 attempts used

Write a YAML header (just the header, between --- lines) for a report that has a title and an author, renders to HTML with a table of contents, and hides the code of every cell by default. Get the nesting right: toc belongs under html, which belongs under format, and echo belongs under execute.

Pasting isn't accepted here — please type your answer so it reflects your own work.

      

Key Points

Proof of completion

Once you've attempted every exercise above, download a PDF summary of your work on this lesson — your name, the exercises you passed, attempt counts, timing, and your final code for each.