Skip to main content

11  Writing and Publishing Books with Quarto

11.1 Learning objectives

A book is more than a collection of documents. It is a coordinated publication in which the sequence of ideas, notation, references, and design supports a reader’s progress. In this chapter we construct a small computational mathematics textbook and use it to investigate the decisions involved in producing a larger work. By the end, you should be able to configure a book, organize its source files, maintain cross-references, separate computational examples from the narrative, customize output formats, and prepare a reproducible release.

11.2 Designing the book before writing

Begin with an audience statement. A book for beginning health-science students should explain mathematical notation before using it in statistical models. A reference for experienced analysts can assume more background. Write measurable objectives for each chapter, identify prerequisites, and decide where readers will practice. A chapter on linear functions might precede regression because the meaning of slope is needed to interpret a fitted model. A chapter on probability should precede inference.

A part groups related chapters; a chapter develops a coherent topic; a section develops one aspect of that topic. Front matter establishes purpose and conventions, while appendices provide supporting material that would interrupt the main narrative. A glossary can help readers locate unfamiliar terminology, but it does not replace definitions at first use.

Maintain a planning table with chapter identifier, objectives, prerequisites, datasets, figures, exercises, reviewer and status. Distinguish a drafted chapter from a reviewed chapter. Page counts are useful production estimates, but they depend on typography, figure placement and output format. Do not infer the final printed length from the number of source files.

11.3 Creating a book project

Run quarto create project book in a terminal and follow the prompts, or create a Book project through a supported editor. The project configuration controls the order of the chapters. File names are not the chapter titles: titles come from headings in the source documents.

project:
  type: book
  output-dir: _book
book:
  title: "Applied Quantitative Models"
  author: "Example Author"
  chapters:
    - index.qmd
    - part: "Mathematical Foundations"
      chapters:
        - chapters/linear.qmd
        - chapters/exponential.qmd
    - references.qmd
  appendices:
    - appendices/computing.qmd
bibliography: references.bib
format:
  html:
    theme: cosmo
    code-copy: true
  pdf:
    documentclass: scrreprt
  docx:
    toc: true
  epub: default

The index introduces the book and provides guidance on its use. The ordered chapter list is authoritative: adding a file to the directory does not automatically insert it into the book. The appendix list distinguishes supporting chapters from the main numbered sequence. Keep bibliography records in a shared file and use consistent citation keys, as discussed in Chapter 7.

A practical directory structure is:

mini-book/
  _quarto.yml
  index.qmd
  chapters/
    linear.qmd
    exponential.qmd
  appendices/
    computing.qmd
  data/
    concentration.csv
  references.bib
  references.qmd
  styles.css

Keep generated output separate from authored source. Do not edit HTML in _book to correct a mathematical error; correct the source and render again. If an illustration is generated by a script, preserve that script as well as the figure. Relative paths make the project portable, but their meaning depends on the execution directory. Test from a fresh copy rather than relying on your editor’s current working directory.

11.4 Establishing a chapter template

A consistent chapter structure helps readers locate explanations, practice and assessment. Begin with a motivating question, then present learning objectives, definitions, worked examples, computational investigations, guided practice, a summary and exercises. Not every section requires code. Explain the mathematical reasoning before asking software to calculate a result.

For a book using both R and Python, present the R implementation first and the Python implementation second, with the same dataset and interpretation. Avoid side-by-side code columns: long lines become unreadable on narrow screens and in print. Use a shared notation convention and make clear whether indices start at zero or one in each language.

Use one top-level heading per chapter and subordinate headings for sections. Give cross-reference identifiers stable, descriptive names, such as sec-linear-model, eq-decay-model, and fig-decay-curve. Avoid embedding chapter numbers in prose references because chapters may be rearranged. For example, @eq-decay-model points to an equation by its identifier rather than its current number.

A numbered equation in a chapter might be written as follows:

$$
C(t)=C_0 e^{-kt}
$$ {#eq-decay-model}

In @eq-decay-model, $k$ is the decay constant.

Check that every identifier is unique across the book. A duplicate identifier can cause a reference to resolve to the wrong object. A heading used for navigation should communicate its topic rather than simply say “Example.”

11.5 Worked investigation: a miniature health-science mathematics textbook

Consider an idealized concentration model. A hypothetical tracer has initial concentration 80 units per liter and a decay constant of 0.2 per hour. We assume a single exponential process and constant conditions. This is a mathematical illustration, not a medication dosing model.

\[ C(t)=80e^{-0.2t},\qquad t\geq 0. \tag{11.1}\]

At five hours the concentration is \(80e^{-1}\approx29.43\). To find the half-life, solve \(80e^{-0.2t}=40\). Dividing by 80 and taking natural logarithms yields

\[ t_{1/2}=\frac{\log 2}{0.2}\approx3.47\text{ hours}. \]

The derivative is \(C'(t)=-0.2C(t)\). Its negative sign indicates that concentration decreases, while the magnitude of the derivative depends on the current concentration. The model approaches zero without reaching zero at any finite time. These properties connect exponential functions, logarithms and calculus.

Idealized tracer concentration over time; the dashed guides identify the half-life.
Figure 11.1: Idealized tracer concentration over time; the dashed guides identify the half-life.

The figure illustrates the difference between a constant proportional decrease and a constant absolute decrease. A linear model with the same initial slope would be \(L(t)=80-16t\). At five hours the linear model reaches zero, whereas the exponential model remains positive. The linear approximation is useful near zero but should not be extrapolated indefinitely.

11.5.1 R implementation

time <- seq(0, 12, length.out = 241)
concentration <- 80 * exp(-0.2 * time)
plot(time, concentration, type = "l", lwd = 2,
     xlab = "Time (hours)", ylab = "Concentration (units/L)")
abline(h = 40, v = log(2)/0.2, lty = 2)
log(2)/0.2

11.5.2 Python implementation

import numpy as np
import matplotlib.pyplot as plt

time = np.linspace(0, 12, 241)
concentration = 80 * np.exp(-0.2 * time)
fig, ax = plt.subplots()
ax.plot(time, concentration)
ax.axhline(40, linestyle="--")
ax.axvline(np.log(2)/0.2, linestyle="--")
ax.set(xlabel="Time (hours)", ylabel="Concentration (units/L)")
plt.show()
print(np.log(2)/0.2)

Both programs implement the same mathematical model. The grid of 241 points controls the smoothness of the plotted curve; it is not a sample of patients. The supplied miniature book contains a linear-model chapter and an exponential-model chapter, together with a small synthetic dataset and computing appendix. Readers can compare the organization of this example with the structure of the present textbook.

11.6 Designing multiple publication formats

A single source does not guarantee identical presentation across formats. HTML is responsive and supports navigation, search and browser-based interactive activities. PDF provides fixed pagination suitable for printing and annotation. Word supports editorial collaboration, while EPUB supports reflowable reading on compatible devices. Choose a primary format and test the others deliberately.

Use quarto preview from the book root for local HTML review. Render individual formats using quarto render --to html, quarto render --to pdf, quarto render --to docx, or quarto render --to epub. PDF requires a working TeX installation. A successful HTML build does not prove that PDF equations, Word tables or EPUB figures will display correctly.

For HTML, use a theme and CSS for typography and spacing. For PDF, choose a suitable document class and use a LaTeX header for additional typesetting rules. Word styles can be customized with a reference document. EPUB supports its own CSS and cover image. These mechanisms are format-specific: CSS does not automatically control LaTeX pagination. See the official book output guide.

Avoid relying on color alone to distinguish curves. Include meaningful alternative text and captions. Use vector graphics where supported, or sufficiently high-resolution raster graphics for print. A figure that looks clear on a desktop may have unreadable axis labels on a phone. Test the smallest intended display size.

11.7 Computational reproducibility and supplementary resources

A computational book should distinguish executable demonstrations from code displayed for study. Executable chunks are appropriate when output needs to update automatically. Nonexecuting fenced examples are useful when readers need to see a command without running it, or when a separate example project isolates dependencies. Explain which approach is used. The miniature book uses nonexecuting examples so the narrative can render without installing both languages; the accompanying scripts can be run separately.

For a mixed-language book, explicitly plan the engine used by each executable document. Do not assume that arbitrary R and Python chunks in one document will automatically use independent kernels. Preserve package requirements and R dependency information, record software versions, and test examples in clean environments. A cached or frozen result is not proof that the current source still executes.

Supply datasets with a data dictionary, units, provenance and licensing information. For healthcare examples, use synthetic or appropriately authorized data. Never include identifiable patient records in a public repository. Separate student-facing exercises from instructor solutions if access restrictions are needed; a hidden navigation link does not protect a file hosted publicly.

11.8 Editions, review and release

Use version control to track changes. Assign a release identifier such as v1.0.0 to a reviewed edition and retain the corresponding source and outputs. A corrected typo may warrant a patch release; a reorganization of chapters may require a new edition. Keep a changelog that describes changes affecting readers and instructors. Record the date and edition in the book metadata and ensure downloadable files correspond to the displayed edition.

A release checklist should include mathematical verification, independent code execution, citation completeness, broken links, duplicate labels, accessibility, print layout, and licensing. Review each output format separately. For online publication, test links under the actual hosting path, not just localhost. Do not publish a draft as a final edition merely because rendering succeeds.

11.9 Guided practice

  1. Create a book with an index, two chapters and an appendix. Reverse the chapter order in YAML and explain what changes after rendering.
  2. Add a numbered equation to the first chapter and refer to it from the second. Rename its identifier and update all references.
  3. Modify the tracer decay constant to 0.1. Predict the half-life before running either script. Explain why it changes.
  4. Render HTML and one additional format. Compare navigation, figure sizing, mathematical notation and code readability. Document any format-specific problems.

11.10 Troubleshooting

Symptom Likely cause Diagnostic action
Chapter absent Missing configuration entry Inspect book.chapters
Unresolved reference Typo or duplicate label Search all source files for identifier
Missing figure Incorrect relative path Check file location and execution directory
PDF fails Missing TeX dependency Run quarto check and inspect error log
Stale result Cached computation Re-execute and verify dependencies
EPUB unreadable table Fixed-width layout Simplify columns and test a reader

11.11 Designing a textbook as a curriculum

A book is more than a collection of documents. Its sequence is an instructional argument: each chapter establishes knowledge that later chapters can use. For a computational mathematics book, begin by identifying the mathematical prerequisites, the computational prerequisites and the authentic applications. A reader who understands exponential functions but has never used a Python array should be able to distinguish a mathematical difficulty from a programming difficulty. Conversely, a reader familiar with programming should not be allowed to substitute a numerical answer for a mathematical justification.

Construct a curriculum map before drafting the chapters. For each chapter record its prerequisites, learning outcomes, central representations, required software and assessment evidence. A chapter on exponential models might require algebra and logarithms, introduce parameter interpretation and graphical reasoning, and culminate in a comparison of a theoretical model with synthetic observations. A subsequent chapter on local approximation can use that same model while introducing derivatives. Reusing the context reduces extraneous cognitive effort without reducing mathematical rigor.

Chapter component Purpose Evidence of completion
Opening application Motivate the mathematical question Reader can articulate the problem
Learning objectives Define expected performance Objectives use observable verbs
Mathematical development Explain definitions and reasoning Assumptions and derivations are explicit
Worked examples Demonstrate a complete reasoning process Intermediate steps are justified
R implementation Connect theory to computation Code reproduces stated benchmarks
Python implementation Offer an equivalent computational route Results agree within tolerance
Visual investigation Explore changes in parameters Reader explains a graphical pattern
Exercises and project Transfer knowledge to new contexts Tasks include interpretation

A reusable chapter template establishes consistency, not uniformity. A proof-intensive chapter may need fewer computational examples and more carefully sequenced arguments. A chapter on regression may require a longer discussion of assumptions, data quality and interpretation. Preserve the common instructional architecture while allowing the mathematical subject to determine the appropriate depth.

11.12 Front matter, back matter and numbering

The preface should identify the intended audience, prerequisites, scope, software requirements and conventions. Explain whether readers need both programming languages or may choose one. A notation guide is useful when the same letter has different meanings in different disciplines. For instance, \(n\) may denote sample size, an iteration count or a matrix dimension. Specify the meaning locally rather than expecting a global glossary to resolve every ambiguity.

Use index.qmd for the opening page of a Quarto book. Acknowledgments and licensing information may appear in the preface or separate pages. Use numbered chapters for the main instructional sequence and appendices for supporting material, such as a programming primer, data dictionary or notation reference. A bibliography can be placed in a dedicated unnumbered chapter containing the refs division. Do not rely on numbered figure or equation references inside unnumbered front matter.

project:
  type: book
  output-dir: _book
book:
  title: "Quantitative Models for Health Science"
  chapters:
    - index.qmd
    - part: "Mathematical foundations"
      chapters:
        - models.qmd
        - approximation.qmd
  appendices:
    - appendix.qmd
format:
  html:
    theme: cosmo
  pdf:
    documentclass: scrreprt
  docx: default
  epub: default
number-depth: 2

The numbering depth determines which heading levels receive numbers; the table-of-contents depth determines which levels appear in navigation. These are distinct editorial decisions. Avoid manually typing chapter numbers into headings because reordering chapters can then produce contradictory numbers. Use stable semantic identifiers for equations and figures, rather than labels containing their current printed numbers. A reference to @eq-edition-decay remains meaningful when the model moves to a different chapter.

11.13 A connected two-chapter mathematical laboratory

The companion edition laboratory uses a hypothetical tracer concentration. It is a mathematical teaching model, not a clinical dosing recommendation. Let \(C_0=80\) and \(k=0.2\) per hour. The model satisfies

\[ C'(t)=-kC(t),\qquad C(0)=C_0. \]

Solving by separation gives \(C(t)=C_0e^{-kt}\). The first chapter develops the model and its half-life. The second chapter references the model equation and derives the tangent approximation at \(a=2\):

\[ L_a(t)=C(a)+C'(a)(t-a)=C_0e^{-ka}[1-k(t-a)]. \]

Because \(C''(t)=k^2C(t)>0\), the curve is strictly convex. Its tangent lies below the curve, except at the point of tangency. This geometric observation explains the sign of the approximation error without requiring numerical experimentation. The numerical experiment then provides evidence consistent with the theorem, rather than serving as its proof.

Exponential curve and tangent at two hours. The tangent touches the curve at two hours and lies below it elsewhere.
Figure 11.2: Exponential curve and tangent at two hours. The tangent touches the curve at two hours and lies below it elsewhere.

For a quantitative error bound, Taylor’s theorem gives \(C(t)-L_a(t)=C''(\xi)(t-a)^2/2\) for some intermediate point \(\xi\). On the interval from two to three hours, \(C''(\xi)\leq 0.04C(2)\). Thus the error at three hours is bounded above by \(0.02C(2)\), approximately 1.073 units. The actual error is approximately 1.004 units. The bound is not an estimate of the actual error; it is a guaranteed upper limit under the mathematical assumptions.

C <- function(t) 80 * exp(-0.2*t)
a <- 2
t <- c(0, 1, 2, 3, 4, 5)
L <- C(a) * (1 - 0.2*(t-a))
result <- data.frame(time=t, exact=C(t), tangent=L,
                     error=C(t)-L)
print(result, digits=5)
stopifnot(all(result$error >= -1e-10))
import numpy as np
import pandas as pd

def C(t):
    return 80 * np.exp(-0.2 * t)

a = 2
t = np.arange(6)
L = C(a) * (1 - 0.2 * (t-a))
result = pd.DataFrame(dict(time=t, exact=C(t), tangent=L,
                           error=C(t)-L))
print(result.round(5))
assert np.all(result.error >= -1e-10)

The two languages implement the same mathematical definition and use the same time grid. A comparison should use unrounded numerical values and an explicit tolerance. Printed tables may use different default rounding conventions, which is not evidence of disagreement. Avoid copying numerical output from one language into the other language’s solution: independent execution is more informative.

11.14 Managing computational dependencies across chapters

A book may contain chapters that require different packages. Document these dependencies centrally, but keep each example sufficiently self-contained that an instructor can run it without executing every preceding chapter. A hidden variable defined in Chapter 2 is not a reliable prerequisite for a code cell in Chapter 8. Explicit imports and local definitions make examples easier to teach, test and reuse.

There are two legitimate approaches to displaying code. Executable cells are appropriate when the book should regenerate its results during rendering. Nonexecuting fences are appropriate for syntax demonstrations, deliberately failing examples and parallel language examples whose execution is verified separately. The edition laboratory adopts the latter approach: a standalone Python generator writes a numerical CSV and a figure, and an independent R script checks the same mathematical results. This reduces the number of execution engines required for the book render itself. It also introduces a responsibility to regenerate the assets before publishing.

A release workflow should run the generator before the render. A frozen or cached result is useful only when its inputs and code still correspond to the source edition. Store the input parameters and output precision policy, and verify that generated files are present. A successful build using stale assets is not a successful computational release. Record interpreter and package versions in the release evidence; a list of package names alone is not an exact environment lock.

11.15 Format-specific editorial laboratories

HTML is well suited to responsive navigation, hyperlinks and interactive investigations. PDF provides fixed pages for printing and handwritten annotation. Word can support editorial review and publisher workflows, while EPUB offers reflowable reading on compatible devices. These are complementary products rather than interchangeable visual copies.

Feature HTML PDF Word EPUB
Navigation Search and links Contents and links Heading navigation Reader-dependent contents
Interactive controls Browser support Static substitute Static substitute Reader-dependent; prefer static
Wide tables Responsive design needed Fit page width Editable but inspect layout Simplify for small screens
Mathematics Browser math rendering TeX typesetting Inspect equation conversion Inspect reader math support
Annotation Browser-dependent Fixed-page annotation Editorial comments Reader-dependent

Do not evaluate a PDF by inspecting only the first page. Check a chapter opening, a long equation, a wide table, a figure with a caption, an exercise page and the bibliography. Inspect page breaks around theorem statements and worked solutions. A figure that is legible on a desktop browser may be too small in print. A table that fits a printed page may require horizontal scrolling on a phone. For EPUB, test a narrow reading viewport and confirm that mathematical symbols and alternative text survive conversion.

The PDF index is a separate feature from the table of contents. A LaTeX index can be configured using makeidx and explicit index entries; those commands do not automatically produce an equivalent HTML or EPUB index. A cross-format glossary with ordinary links is often a more portable complement. Do not promise an index in every edition unless each output has actually been inspected.

11.16 Edition management and independent editorial review

A release should identify the exact source revision, the edition, the output formats, the computational environment and the review status. Keep a correction ledger with the location, original statement, corrected statement, reason and affected outputs. When a mathematical parameter changes, trace its consequences through the derivation, table, figure, exercise and instructor solution. A correction is not complete until all affected representations agree.

For example, replacing the decay constant 0.2 with 0.1 doubles the half-life. It also changes the tangent slope, the plotted curve and all numerical examples. An editor who updates only the equation creates an inconsistent textbook. In the edition laboratory the parameter file is the authoritative computational input; the generator produces a table and figure from it. Narrative statements still need review. An automated source audit checks configured files, duplicate labels and unresolved references within a deliberately restricted syntax. It is not a replacement for Quarto’s actual cross-reference processing or a complete Markdown parser.

An independent reviewer should receive the source project, not merely a PDF. Ask the reviewer to regenerate the numerical assets, compare the results with the supplied benchmarks and render at least one format. Record which checks passed, which failed and which could not be performed. A reviewer who lacks a TeX installation can still verify the mathematical calculations and HTML source, but must not mark PDF layout as passed.

11.17 Extended guided practice

  1. Construct a curriculum map for a three-chapter book on functions, derivatives and optimization. Identify one mathematical and one computational prerequisite for each chapter.
  2. Explain why a preface should not be used as the location of a numbered theorem needed by later chapters.
  3. Rename the model equation identifier in the edition laboratory and update the reference in the approximation chapter. Run the source audit before and after the change.
  4. Derive the tangent equation at two hours without using software. Compare the exact and approximate values at three hours.
  5. Prove that the tangent underestimates the exponential curve and explain the role of convexity.
  6. Change the decay constant to 0.1 in the parameter file. Regenerate the assets and identify every narrative statement requiring revision.
  7. Compare the numerical results from the R and Python implementations using a tolerance of \(10^{-9}\).
  8. Introduce a duplicate equation identifier and explain why the audit should reject the project.
  9. Prepare an acceptance matrix for HTML, PDF, Word and EPUB. Distinguish source checks from rendered-output checks.
  10. Write a release note explaining a corrected mathematical error and identify the affected student and instructor materials.

11.18 Extended project: a multi-format textbook edition

Develop a two-chapter computational mathematics book with an explicit curriculum map, a preface, sequential R and Python examples, an appendix and a documented release process. Include one mathematical model that connects the chapters, a numbered equation referenced from the second chapter, a generated table, a publication-quality figure and a worked exercise with a separate instructor solution. Introduce a controlled parameter change, regenerate the computational assets and document the editorial changes required. Submit the source, available rendered editions and an honest acceptance matrix.

Criterion Points
Curriculum architecture and consistent chapter design 6
Mathematical development and cross-chapter coherence 8
Computational reproducibility and generated assets 6
Format-specific editorial review 5
Edition documentation and independent verification 5
Total 30

11.19 Chapter summary

A Quarto book coordinates chapters, references and output settings through a shared configuration. Effective books combine coherent instructional design with stable identifiers, portable data and code, format-specific testing and a documented release process. The source project, rather than any one rendered edition, is the authoritative record of the publication.

11.20 Review exercises

  1. Explain the difference between a book and a website project.
  2. What determines chapter order?
  3. Why separate source and generated output?
  4. Describe the purpose of front matter.
  5. When should material be placed in an appendix?
  6. Why use stable cross-reference identifiers?
  7. Explain why R and Python examples should use the same data.
  8. Distinguish executable and nonexecuting code fences.
  9. Calculate the tracer concentration at ten hours.
  10. Derive the half-life for a general positive decay constant.
  11. Compare HTML and PDF for classroom annotation.
  12. Why test EPUB independently?
  13. What is a Word reference document used for?
  14. Explain why a public repository is unsuitable for confidential data.
  15. What information belongs in a changelog?
  16. Explain why a successful render is insufficient evidence of publication readiness.

11.21 Applied project: publish a miniature textbook

Create a two-chapter quantitative health-science textbook with a preface, appendix, bibliography and a consistent chapter template. Include a mathematical model, a labeled equation, a table, a figure, and sequential R and Python examples. Provide a synthetic dataset and data dictionary. Render HTML and one additional format where software permits. Submit the source archive, rendered outputs, and a release checklist identifying any unverified steps.

Criterion Points
Project organization and metadata 5
Mathematical accuracy and explanations 5
Reproducible R and Python examples 5
Figures, tables and cross-references 5
Output testing and release documentation 5
Total 25

11.22 Further reading

11.23 Supplemental assessment

  1. Conceptual (4 points). Explain why chapter numbering should not be hard-coded.
  2. Technical (8 points). Build a two-chapter book with a labeled equation in chapter one and a reference in chapter two.
  3. Applied (8 points). Prepare HTML and PDF editions with identical mathematical content and a release checklist.

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

11.24 Looking ahead

Add interactive investigations and static alternatives in Chapter 12.

11.25 Interactive learning lab

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

Open the activity in its own page.