Skip to main content

3  Markdown, YAML, and Document Structure

A clinical research team has completed a pilot study of a patient education program. Its report must be readable by clinicians, reproducible by analysts, and suitable for distribution as a PDF. The team has collected data and written its conclusions, but the document is difficult to navigate: headings are inconsistent, tables lack units, and important limitations are buried in long paragraphs. These are problems of document architecture, not statistical computation. This chapter develops the authoring skills that make a Quarto publication useful to its readers.

3.1 Learning objectives

After completing this chapter, you should be able to distinguish content from presentation, use Markdown to express document structure, construct valid YAML metadata, incorporate accessible figures and tables, distinguish executable cells from code listings, and adapt a source document to multiple output formats. You will also learn to diagnose errors by isolating the smallest source fragment that reproduces a problem.

3.2 Content, structure, and presentation

A conventional word processor encourages authors to manipulate the appearance of individual paragraphs. A structured authoring system instead asks authors to identify the role of each element. A heading is not merely large bold text: it identifies a section and its relationship to other sections. A table is not an arrangement of spaces: it expresses relationships between observations and variables. This distinction enables software to generate navigation, apply consistent typography, and convert the same source into different formats.

Consider a report with sections called Methods, Results, and Limitations. In HTML, readers may navigate to these sections through a sidebar. In PDF, the same headings may appear in a numbered table of contents. In Word, they may be represented by heading styles. The source author does not need to manually recreate these features for every format. However, exact visual equivalence is neither guaranteed nor desirable: a wide interactive chart may need a static alternative on paper.

NoteSemantic authoring

Choose a markup element because of what it means, not merely because of how it looks in one output format.

3.3 Markdown fundamentals

Markdown is a plain-text notation for expressing document structure. A Markdown paragraph consists of text separated from adjacent paragraphs by blank lines. A single newline within a paragraph normally behaves like a space in rendered prose. Do not insert repeated spaces or blank paragraphs to force a particular layout; use the appropriate structural element or format-specific settings.

3.3.1 Emphasis and inline code

Source Intended result
*pilot study* Italic emphasis
**Primary outcome** Strong emphasis
`mean()` Literal code or identifier
~~obsolete~~ Strikethrough

Use emphasis selectively. In a statistical report, bold text may identify a key conclusion, but bolding an entire paragraph weakens its usefulness. Inline code is especially valuable when a variable name such as WaitMinutes must be distinguished from ordinary prose. A reader should be able to copy the identifier without guessing its spelling.

3.3.2 Headings and hierarchy

# Clinic waiting-time report

## Methods

### Participants

### Measurement procedure

## Results

## Limitations

The number of hash characters determines the heading level. Include a space after the hashes. In a standalone document, the title is often supplied through YAML and body sections begin at level two or level one according to the desired hierarchy. In a Quarto book, the chapter heading normally begins with one hash, and its sections begin with two. Avoid skipping levels solely to obtain smaller typography. A skipped level can make the document outline harder to interpret, especially for assistive technologies.

3.3.3 Lists and nested structure

Use unordered lists for collections without a required sequence and ordered lists for procedures. The distinction matters in a laboratory protocol: changing the order of steps may change the result.

1. Import the dataset.
2. Check the variables.
   - Verify measurement units.
   - Identify missing observations.
3. Calculate the summaries.

Indent nested items consistently. When a list does not render correctly, insert a blank line before it and inspect the indentation. For a paragraph belonging to a list item, indent it to align with the item’s content rather than with its marker.

3.4 YAML: metadata and configuration

YAML expresses structured information through mappings, sequences, and scalar values. A mapping associates a key with a value. A sequence contains an ordered collection. A scalar is an individual value such as a string, number, or Boolean. Quarto reads YAML metadata at the beginning of a document, between lines containing three hyphens.

---
title: "Clinic Waiting Times: A Pilot Study"
author: "Research Methods Team"
format:
  html:
    toc: true
    code-copy: true
  pdf:
    toc: true
  docx: default
---

Here, title and author are strings. The format key contains a mapping of output formats. Under html, the two indented options belong to that format only. The value true is a Boolean, not the string "true". The colon within the title is protected by quotation marks.

3.4.1 Indentation and sequences

keywords:
  - reproducibility
  - clinical research
  - patient experience

Use spaces rather than tabs for indentation. Two spaces per level is a convenient convention. Sibling keys must align. A sequence item begins with a hyphen followed by a space. Do not confuse the sequence marker with the three-hyphen delimiter around document metadata.

The following is incorrect because toc is not nested under html as intended:

format:
  html:
  toc: true

Although a YAML parser may accept this as a mapping, Quarto may reject or misinterpret its structure. Correct YAML syntax is necessary but not sufficient: the keys must also be valid Quarto options in their particular context.

3.4.2 Document and project configuration

A standalone report may contain its complete configuration in its own header. A book usually shares common settings in _quarto.yml. This allows an author to set a theme, bibliography, or output format once rather than repeat it in every chapter. Document metadata can override many inherited settings, but some options are project-specific. Consult the relevant format reference before assuming an option is available at every level.

When troubleshooting, examine both the document header and the project configuration. A report may behave differently inside a project than when copied to a separate directory. The surrounding configuration is part of the reproducible environment.

3.5 Tables and figures

3.5.1 Constructing a readable table

A table should answer a question. For a clinic manager, a table of waiting times by appointment type may be more informative than a list of patient identifiers. Include units in column headings, report the sample size, and distinguish missing values from zero.

| Appointment type | Patients | Mean wait (min) |
|:-----------------|---------:|----------------:|
| Routine          | 3        | 15.0            |
| Follow-up        | 3        | 10.0            |

: Waiting times by appointment type. {#tbl-example-waits}

The colons in the separator row specify alignment. Numeric columns are commonly right-aligned to support comparison. The caption follows the table after a blank line. A label beginning with tbl- permits a Quarto cross-reference.

Table 3.1: Waiting times in a synthetic pilot dataset.
Appointment type Patients Mean wait (min)
Routine 3 15.0
Follow-up 3 10.0

The difference in Table 3.1 is descriptive. The six observations do not establish that appointment type causes a change in waiting time. A well-structured report makes this limitation visible near the result rather than hiding it in an appendix.

3.5.2 Images, captions, and alternative text

![Waiting times by appointment type.](../figures/ch03-waits.png){#fig-example-waits fig-alt="Routine waits are 10, 15 and 20 minutes; follow-up waits are 5, 10 and 15 minutes." width=85%}

The path is relative to the source file. The label begins with fig-, and the alternative text communicates the substantive information for readers who cannot see the image. A caption identifies the figure and its context; alternative text describes what is visually important. Do not assume the filename is an adequate description.

Routine waits are 10, 15 and 20 minutes; follow-up waits are 5, 10 and 15 minutes.
Figure 3.1: Waiting times in a synthetic clinic pilot study.

In Figure 3.1, the two groups overlap. Displaying individual observations is useful for small samples because an average alone conceals variation. Avoid presenting a decorative three-dimensional chart when a simple dot plot communicates the result more directly.

3.6 Mathematics and technical notation

Use single dollar delimiters for inline mathematics and double dollar delimiters for displayed equations. The mathematical content uses LaTeX-style notation even when the final publication is HTML.

The sample mean is $\bar{x}$.

$$
\bar{x}=\frac{1}{n}\sum_{i=1}^{n}x_i
$$ {#eq-example-mean}

The sample mean is \(\bar{x}\), defined by

\[ \bar{x}=\frac{1}{n}\sum_{i=1}^{n}x_i. \tag{3.1}\]

In Equation 3.1, \(n\) is the number of observations and \(x_i\) denotes observation \(i\). Define symbols in surrounding prose; a correctly typeset formula is not necessarily a well-explained formula. For the routine group, the mean is \((10+15+20)/3=15\) minutes. When the observations change, the numerical value must change as well. Chapter 4 introduces ways to compute and insert such values automatically.

3.7 Code listings and executable cells

A fenced code listing displays source code without executing it. An executable cell has a language identifier enclosed in braces. This small syntactic distinction has major consequences for reproducibility.

```r
mean(c(10, 15, 20))
```

```{r}
#| echo: true
mean(c(10, 15, 20))
```

The first block displays R code. The second requests execution by the appropriate engine. Cell options use lines beginning with #|. For example, echo: false hides the source while retaining its results, and eval: false prevents execution. include: false suppresses the cell’s visible content while allowing execution unless evaluation is disabled separately. Hiding code is a presentation decision, not a substitute for documenting the analysis.

3.7.1 R implementation

wait <- c(10, 15, 20, 5, 10, 15)
group <- rep(c("Routine", "Follow-up"), each = 3)
aggregate(wait ~ group, FUN = mean)

3.7.2 Python implementation

from statistics import mean
routine = [10, 15, 20]
follow_up = [5, 10, 15]
print({"Routine": mean(routine), "Follow-up": mean(follow_up)})

Both examples produce group means of 15 and 10 minutes. They are supplied as separate executable documents in the companion examples folder so that readers can select an engine without configuring a mixed-language document. In this chapter, the listings themselves are intentionally nonexecuting.

3.8 Callouts and document organization

Quarto supports fenced divs for grouping content. A callout is one common application. Use callouts for information that deserves a distinct visual treatment, such as a warning or a practical tip.

::: {.callout-warning}
## Interpretation

The pilot study does not establish causality.
:::
WarningInterpretation

The pilot study does not establish causality. Appointment type may be associated with staffing, scheduling, or other factors.

Do not place every paragraph inside a callout. Too many competing visual signals obscure the hierarchy of information. Also verify how callouts appear in the intended output formats, because presentation varies across formats.

3.9 Designing a complete academic report

A coherent report starts with the question, explains how evidence was collected, presents the results, and interprets them in light of the design. For the clinic example, the research question is whether observed waiting times differ between appointment types. The methods identify the six synthetic observations and the unit of measurement. Results include the group means and individual observations. Limitations explain that the sample is small and synthetic. Conclusions state the descriptive difference without implying a causal effect.

The companion examples/ch03/clinic-report.qmd demonstrates this organization without requiring an execution engine. Render it in HTML first, inspect the headings and table, and then render Word or PDF if the necessary software is installed. Compare the outputs for content consistency, rather than demanding identical pagination.

3.10 Guided practice

3.10.1 Activity 1: Repair a document outline

A draft has a level-one heading for Methods, a level-four heading for Participants, and a level-two heading for Results. Rewrite the outline so that Methods and Results are peers and Participants is subordinate to Methods. Explain why the revised outline improves navigation.

3.10.2 Activity 2: Debug metadata

Correct the following header. Identify both the quoting problem and the indentation problem.

---
title: Clinic report: November
format:
  html:
  toc: true
---

Render the corrected source and verify that the table of contents appears after you add at least two headings.

3.10.3 Activity 3: Improve a table

Create a table for three routine observations (10, 15, 20 minutes) and three follow-up observations (5, 10, 15 minutes). Include group sizes and means, a caption, a unique label, and a sentence that references the table. Explain why reporting only the two means is insufficient to describe variation.

3.10.4 Activity 4: Compare code visibility

Copy the R or Python companion report. Render it with echo: true, then with echo: false. Finally set eval: false and render again. Record which elements appear in each output. Restore the original settings before submitting the report.

3.11 Troubleshooting systematically

Symptom Likely cause First diagnostic action
Metadata appears as prose Missing delimiter Inspect the first lines of the file
YAML parser error Indentation or quoting Reduce header to title and format
Heading appears as plain text Missing space after hash Inspect source characters
Table appears as prose Malformed separator row Check column counts and blank lines
Figure is missing Incorrect relative path Verify file location from source directory
Reference shows a question mark Label mismatch Compare label and reference exactly
Code appears without results Nonexecuting fence or eval disabled Inspect fence and cell options

Start with a minimal document that renders. Add one element at a time until the error returns. Keep the first meaningful error message, not only the last line of a long log. If a document renders in HTML but not PDF, investigate format-specific dependencies before rewriting working Markdown.

3.12 Designing a document around its reader

A well-organized report allows readers to answer three questions quickly: What was investigated? What evidence was obtained? What can reasonably be concluded? These questions determine the order of the sections. A clinic manager may need an executive summary before the methods, whereas a scientific reviewer needs sufficient detail about recruitment and measurement to evaluate the evidence. The same numerical analysis can support both publications, but the narrative and level of detail should differ.

Begin by writing a short purpose statement before creating the headings. For example, “This report compares observed waiting times for routine and follow-up visits in a synthetic pilot dataset.” This statement specifies the outcome, the comparison, and the scope. It does not imply that appointment type causes a change in waiting time. Next, create an outline in which each heading answers a distinct question. A methods section describes how observations were obtained; a results section reports the summaries; a discussion section interprets those summaries in context. Avoid placing new numerical results in the limitations section where readers are unlikely to find them.

3.12.1 Worked example: transforming an unstructured paragraph

Suppose an analyst writes: “We measured six visits, the routine mean was 15 minutes, follow-up was 10 minutes, and we do not know whether staffing was comparable.” The sentence contains methods, results and limitations. Rather than applying bold formatting to selected words, separate the information into three semantic sections:

## Methods

Six synthetic visit records were grouped by appointment type.
Waiting time was measured in minutes.

## Results

The mean waiting time was 15 minutes for routine visits
and 10 minutes for follow-up visits.

## Limitations

Staffing levels were not recorded. The observed difference
cannot establish a causal effect of appointment type.

This revision does not change the evidence. It changes how the evidence can be located and evaluated. The same headings can populate an HTML navigation menu or a printed table of contents. In a longer report, subsections can distinguish the study population, measurement procedure and analysis plan without requiring manual numbering.

3.12.2 Guided practice: outline before formatting

Write two outlines for the same six records: a one-page briefing for a clinic manager and a methods-focused report for a research supervisor. Include the same observed means and limitations in both. Explain which details should appear earlier in each document and why. Do not remove uncertainty simply because the intended audience is nontechnical.

3.13 Metadata as a reproducibility contract

YAML describes properties of a publication that are separate from its narrative. The title, author, date, output format and execution settings are metadata. A reader who opens the source should be able to identify the intended output without searching through prose or guessing which button the author used.

3.13.1 Mappings, sequences and scalar values

A mapping associates a key with a value; a sequence represents an ordered collection. A scalar is a single value such as a string, Boolean or number. These concepts are more important than memorizing individual settings because they allow readers to interpret unfamiliar configuration files.

 title: "Clinic report: pilot analysis"
 author:
   - name: Example Researcher
     affiliation: Example University
 format:
   html:
     toc: true
     number-sections: true
   docx: default

The leading indentation in this illustrative mapping should be removed when copying it to the top level of a document header. The author field is a sequence containing one mapping. The format field is a mapping containing two output formats. The HTML options are nested beneath html, so they do not automatically become Word options. A colon followed by a space inside a title should be protected with quotation marks. Use spaces rather than tabs for indentation.

3.13.2 Configuration inheritance in a project

A project configuration file named _quarto.yml supplies settings shared by documents in that project. A directory-level _metadata.yml can provide settings for documents in a particular directory. Document front matter can specify local settings. This arrangement reduces duplication but creates a responsibility to understand where a setting originates. For ordinary scalar settings, more local metadata generally takes precedence; do not assume that every nested list is replaced in the same way. Inspect the effective configuration and render a representative document whenever changing shared settings.

For example, a research project can specify HTML as the default format, a table of contents and numbered sections. A short executive summary can disable the table of contents locally. This is preferable to copying an entire project configuration into every file. Conversely, if a document must be distributed independently, include the metadata necessary for it to render outside the project.

3.13.3 Laboratory: shared and local settings

The companion metadata-lab project contains a shared configuration and two reports. Render the project from its root directory. Compare the navigation in the two reports, then change the shared toc setting and render again. Record which report changes and which retains its explicit local setting. Restore the original configuration before submitting. Use quarto inspect to investigate the project if the observed result differs from your prediction.

3.14 Mathematical statements as structured content

Mathematical notation is not simply decoration. It identifies quantities, relationships and assumptions. A report that states a mean without defining the denominator leaves readers uncertain about the observations included in the calculation. Use inline mathematics for short expressions and displayed mathematics for definitions or derivations that need visual separation.

For a group of \(n_g\) visits with observed waiting times \(x_{gi}\), define the sample mean as

\[ \bar{x}_g=\frac{1}{n_g}\sum_{i=1}^{n_g}x_{gi}. \tag{3.2}\]

Equation Equation 3.2 defines a descriptive statistic, not a population parameter. In this example, the group sizes are both three. The observed difference, follow-up minus routine, is \(10-15=-5\) minutes. Always identify the subtraction order and the measurement units. A negative value is meaningful only in relation to that definition.

3.14.1 Semantic environments and callouts

Use a callout to distinguish a warning, note or important interpretation from surrounding prose. A limitation should not be hidden in a collapsed callout if it is essential to understanding the results. Use theorem-like environments when a mathematical statement requires a stable label and reference. Do not label every paragraph as a theorem: a worked calculation, a definition and a scientific claim have different logical roles.

::: {.callout-important}
## Interpretation

The observed difference is descriptive and does not establish causality.
:::

A callout may have different typography in HTML and PDF. Its meaning should survive even if color or icons are unavailable. Avoid referring to “the green box” in prose; refer instead to its title or content.

3.15 Tables, figures and the evidence trail

A table is useful when exact values matter; a figure is useful when patterns or variation matter. A report should not duplicate every table in a figure without a reason. For the clinic example, a summary table provides group means and sample sizes, while a dot plot shows the overlap between the groups. Together they prevent readers from confusing a difference in averages with complete separation of the observations.

Table 3.2: Descriptive summaries of synthetic waiting times.
Appointment type Observed visits Mean (min) Sample SD (min)
Routine 3 15 5
Follow-up 3 10 5
Two rows of dots show overlapping waiting times, with the routine group shifted five minutes to the right.
Figure 3.2: Waiting times by appointment type. Routine observations are 10, 15 and 20 minutes; follow-up observations are 5, 10 and 15 minutes.

Table 3.2 and Figure 3.2 communicate complementary information. Both groups have a sample standard deviation of five minutes, although their means differ. A reader can see that a routine visit may have a shorter wait than a follow-up visit. The figure uses a common horizontal scale and direct group labels, rather than relying on color alone.

3.15.1 Stable labels and references

Use meaningful identifiers such as fig-wait-distribution instead of fig-1. Quarto assigns numbers during rendering. If a figure is moved earlier in the manuscript, its reference can update without rewriting the surrounding sentence. Prefixes such as fig-, tbl- and eq- identify the type of referenced object. Keep identifiers unique across a book, including its appendices. A caption describes the content and context; alternative text conveys essential visual information to a reader who cannot see the figure. Neither replaces the other.

3.15.2 Guided practice: a missing observation

Imagine the final routine waiting time is missing rather than 20 minutes. The routine mean becomes 12.5 minutes based on two observations. Revise the table, figure caption, alternative text and interpretation together. The follow-up mean remains 10 minutes. Explain why replacing the missing value with zero would produce a different and potentially misleading result. Preserve the original data and record the correction separately.

3.16 Sequential computational authoring in R and Python

A document can present both languages for teaching without executing both engines in a single source file. The companion reports use separate documents and a shared CSV file. This design makes the execution environment explicit and lets students compare the numerical outputs independently. The following listings are not executed as part of the book itself.

3.16.1 R implementation

visits <- read.csv("visits.csv")
stopifnot(all(is.finite(visits$wait_min)))
aggregate(wait_min ~ group, visits, mean)
aggregate(wait_min ~ group, visits, sd)

3.16.2 Python implementation

import pandas as pd
visits = pd.read_csv("visits.csv")
assert visits["wait_min"].notna().all()
print(visits.groupby("group")["wait_min"].agg(["count", "mean", "std"]))

The R sd() function and pandas std() use the sample standard deviation by default. A NumPy implementation would require ddof=1 to obtain the same convention. Agreement between two implementations is useful evidence, but it does not establish that the research design is appropriate. Both programs could faithfully compute the wrong statistic if the research question were incorrectly defined.

3.17 A format-aware editorial laboratory

Render the companion report to HTML first. Inspect the headings, the table of contents, the equation, the figure and its references. Next render to Word, if available, and inspect whether the table fits the page and the headings remain editable. Finally attempt PDF if a TeX distribution is configured. Do not equate a successful exit status with a successful publication: a figure can be clipped, a reference can remain unresolved, and a table can be difficult to read even when the rendering command completes.

quarto render report.qmd --to html
quarto render report.qmd --to docx
quarto render report.qmd --to pdf

The report is intentionally prose-only and uses a precomputed figure so that this laboratory isolates document structure from computational dependencies. The separate R and Python reports demonstrate execution. If PDF fails while HTML works, preserve the error log and investigate the TeX environment rather than rewriting correct Markdown. For each output, record the format, command, software version, observed defects and corrective action. If a format is unavailable, mark it untested rather than passed.

3.18 Extended applied project: a two-audience research publication

Prepare a technical report and a short clinic briefing from the shared synthetic dataset. Use a common data dictionary, explicit measurement units, and consistent numerical results. The technical report should include methods, a labeled equation, a summary table, a figure with alternative text, and a limitations section. The briefing should emphasize the observed difference and its uncertainty without claiming causation. Include a separate executable R or Python report and a record of the rendered formats. Ask a peer to locate the denominator, reproduce the mean, and identify the main limitation without consulting you.

Criterion Points
Logical hierarchy and audience-appropriate organization 6
Valid metadata and reusable configuration 5
Accurate calculations and mathematical notation 6
Accessible tables, figures and references 6
Format-specific review and peer reproduction evidence 7
Total 30

3.19 Chapter summary

Markdown expresses the logical structure of a document; YAML supplies metadata and configuration. Headings, tables, figures, equations, and callouts communicate different kinds of information. Code fences distinguish source listings from computations. Cross-references connect narrative to evidence without manually maintaining numbering. A professional document combines accurate content, accessible structure, and deliberate format choices.

3.20 Review exercises

  1. Explain the distinction between semantic structure and visual formatting.
  2. Write Markdown for a heading, emphasized phrase, and inline variable name.
  3. Construct a three-level outline for a research report.
  4. Explain when an ordered list is preferable to an unordered list.
  5. Write a descriptive link to the official Quarto documentation.
  6. Explain the difference between a YAML mapping and sequence.
  7. Write a header containing a title with a colon and HTML table of contents.
  8. Explain why syntactically valid YAML can still be invalid Quarto configuration.
  9. Construct a table with right-aligned numeric columns and a caption.
  10. Explain the difference between a figure caption and alternative text.
  11. Write a displayed equation for the sample mean and define its symbols.
  12. Distinguish a code listing from an executable R cell.
  13. Compare echo: false, eval: false, and include: false.
  14. Explain why a small descriptive study cannot establish causality by itself.
  15. Diagnose an unresolved figure reference.
  16. Explain why HTML and PDF outputs need not look identical.

3.21 Applied project: A professional clinic report

Prepare a Quarto report for a clinic quality-improvement team using the six synthetic observations introduced in this chapter. Include a title and author in YAML, a table of contents, a research question, methods, a labeled table, a labeled figure with alternative text, an equation defining the mean, and a limitation callout. Include a code listing or executable cell in your chosen language. Render HTML and one additional format if available; if the second format fails, submit the diagnostic log and explain the dependency issue. Submit the source and all required assets together.

Criterion Points
Valid metadata and logical heading structure 5
Accurate summaries and clear units 5
Accessible figure and table with references 5
Mathematical notation and code presentation 4
Interpretation and limitations 4
Organized source and rendering evidence 2
Total 25

3.22 Further reading

3.23 Supplemental assessment

  1. Conceptual (4 points). Distinguish document metadata from body content.
  2. Technical (8 points). Write YAML for an HTML report with title Clinic Summary and toc enabled; create two level-two headings.
  3. Applied (8 points). Produce a reader-facing report and an analyst-facing report from a shared source; explain what differs.

See the student assessment packet in the source package for submission guidance and any required datasets.

3.24 Looking ahead

Apply document structure to executable R reports in Chapter 4.

3.25 Interactive learning lab

Explore the activity below, then explain what changed and why.

Open the activity in its own page.