Reproducible Research with R Markdown

Reproducible Research with R Markdown in R: In a print shop before digital layout, a compositor built a page on a paste-up board: a rigid sheet ruled into…

The Analogy: A Print Shop's Paste-Up Board

In a print shop before digital layout, a compositor built a page on a paste-up board: a rigid sheet ruled into columns on a light table. Galleys of set type -- long strips of printed text -- were trimmed and waxed and burnished down into their columns, and rectangular gaps were left where photographs and charts would go. The board was the master. It carried the words and it reserved the exact space for every figure, but the figures themselves were not yet on it; the slots sat empty, each marked with the name of the plate that belonged there.

An R Markdown document is that board. The source file interleaves two things: narrative prose, which is the set type waxed into its columns, and code chunks, which are the reserved slots waiting for a figure. You write and edit the board -- the prose and the code that will fill the slots -- and nothing else. The prose is fixed text you author directly, and each code chunk is a labelled gap that says, in effect, "the plate produced by running this code goes here." What you never do is paint a finished figure onto the board by hand; you describe how to produce it.

Knitting is pulling a proof. The press inks the whole board in one pass and presses it onto paper, and only then do the reserved slots fill: each chunk is run, its output -- a table, a plot, a single computed number -- is captured, and that output is dropped into the slot the chunk marked. The proof that comes off the press shows the words and the freshly generated figures together as one page. Run the press again on the same board and you get the same proof, because every figure on it was produced from the board, not pasted on afterward.

The discipline that makes this work is that the board and the proof must never drift apart. A compositor who spots a wrong figure on the proof and inks a correction onto the proof itself -- rather than fixing the board -- has thrown that correction away, because the next pull comes from the board and reproduces the original error. The far worse mistake is pasting a number straight into the prose: a value copied from a one-off calculation into a sentence, tied to no chunk. It looks reproducible, but on the next knit the real chunks regenerate their figures while the pasted number sits frozen, and now the document quietly contradicts itself. Reproducibility holds only when every computed thing on the page traces back to a chunk that re-runs when you knit; anything hand-placed is a correction inked onto the proof, lost on the next pull.

Syntax or Core Structure

An R Markdown document mixes prose and named code chunks, and knitting runs the chunks and splices their output into the rendered page. To show the mechanics without nesting document fences, this lesson uses the knitr::spin convention, which expresses the same idea in a plain .R script: a line beginning with #' is prose, a line beginning with #+ sets a chunk's options, and every other line is code. The script below has one prose block, one options line, and one chunk.

#' # Quarterly Revenue Report
#' Revenue by region for the quarter, in thousands.

#+ revenue-table, echo=FALSE
region  <- c("North", "South", "East")
revenue <- c(120, 95, 143)
total   <- sum(revenue)

writeLines(sprintf("%-10s%10s", "REGION", "REVENUE"))
writeLines(strrep("-", 20))
for (i in seq_along(region)) {
  writeLines(sprintf("%-10s%10d", region[i], revenue[i]))
}
writeLines(strrep("-", 20))
writeLines(sprintf("%-10s%10d", "total", total))

#' The table above is generated, never typed by hand.

When this is knitted, the revenue-table chunk runs and the text it prints is captured and placed into the document exactly where the chunk sat. That captured output is:

Output:

REGION       REVENUE
--------------------
North            120
South             95
East             143
--------------------
total            358

The prose lines above and below become the report's headings and sentences; the chunk's printed table becomes the figure between them. Nobody typed 358 into the document -- sum produced it, and if a region's revenue changes, the next knit recomputes the total and the table redraws itself. The echo=FALSE option means the reader sees the table but not the code that made it, which is the print-shop board handing over a clean proof with no layout marks showing.


Technical Depth: How Knitting Assembles the Page

The document is a sequence of prose and code

Before anything runs, a knitting engine parses the source into an ordered list of pieces: prose to copy through untouched, and code to execute. In the spin convention that split is a line-by-line classification -- #' marks prose, #+ marks a chunk's options, and everything else is code to run. Seeing that classification makes the structure concrete.

lines <- c(
  "#' # Nitrate report",
  "#' Readings for the quarter:",
  "#+ setup, echo=FALSE",
  "x <- c(47, 49, 52)",
  "mean(x)"
)
classify <- function(l) {
  if (startsWith(l, "#'")) "prose"
  else if (startsWith(l, "#+")) "options"
  else "code"
}
kind <- vapply(lines, classify, character(1))

writeLines(sprintf("%-14s: %d", "total lines", length(lines)))
writeLines(sprintf("%-14s: %s", "kinds", paste(unname(kind), collapse = " ")))
writeLines(sprintf("%-14s: %d", "prose", sum(kind == "prose")))
writeLines(sprintf("%-14s: %d", "options", sum(kind == "options")))
writeLines(sprintf("%-14s: %d", "code", sum(kind == "code")))

Output:

total lines   : 5
kinds         : prose prose options code code
prose         : 2
options       : 1
code          : 2

The engine now knows the shape of the document: which lines to copy verbatim, which set options, and which to run. Prose is never executed and code is never printed as prose; the classification is what keeps the two streams from bleeding into each other.

Chunk options decide what reaches the page

Each chunk carries options that control its contribution to the output. Three do most of the work: echo shows or hides the source code, eval runs or skips the code, and include admits or suppresses everything the chunk would contribute. The visible code appears only when the code is echoed and the chunk is included; the visible output appears only when the code is evaluated and the chunk is included.

OptionControlsSet FALSE to
echoWhether the source code is shownHide code, keep its output
evalWhether the code is runShow code as a non-run listing
includeWhether anything from the chunk appearsRun for side effects, show nothing
messageWhether package messages appearSilence library load chatter
warningWhether warnings appearKeep warnings out of the report

Working the first three options through four chunks shows the combinations a real report uses:

chunks <- data.frame(
  name    = c("setup", "table", "source", "draft"),
  echo    = c(FALSE, FALSE, TRUE, TRUE),
  eval    = c(TRUE, TRUE, TRUE, FALSE),
  include = c(FALSE, TRUE, TRUE, TRUE)
)
writeLines(sprintf("%-10s%-6s%s", "CHUNK", "CODE", "OUTPUT"))
writeLines(strrep("-", 22))
for (i in seq_len(nrow(chunks))) {
  code_shown   <- chunks$echo[i] && chunks$include[i]
  output_shown <- chunks$eval[i] && chunks$include[i]
  writeLines(sprintf("%-10s%-6s%s", chunks$name[i],
                     if (code_shown) "yes" else "no",
                     if (output_shown) "yes" else "no"))
}

Output:

CHUNK     CODE  OUTPUT
----------------------
setup     no    no
table     no    yes
source    yes   yes
draft     yes   no

The setup chunk runs but shows nothing -- it loads packages and data for later chunks, with include=FALSE. The table chunk hides its code but shows its output, the common pattern for a clean report. The source chunk shows both, for a tutorial that teaches the code. The draft chunk shows the code but does not run it, because eval=FALSE -- useful for displaying an example you are not ready to execute. Every visible combination on the page is one of these option settings.

Inline weaving splices values into prose

Beyond whole-chunk output, a report weaves single computed values into sentences, so a number in the narrative stays in step with the data. The mechanism is substitution: a placeholder in the text is replaced by the value of an expression at knit time. This model uses {{...}} placeholders to make the splice visible.

x <- c(44, 45, 46, 47, 48, 45, 47, 48)
template <- "The mean nitrate reading is {{m}} across {{n}} samples."
woven <- template
woven <- sub("\\{\\{m\\}\\}", sprintf("%.2f", mean(x)), woven)
woven <- sub("\\{\\{n\\}\\}", length(x), woven)

writeLines(sprintf("%-10s: %s", "template", template))
writeLines(sprintf("%-10s: %s", "woven", woven))
writeLines(sprintf("%-10s: %d", "samples", length(x)))
writeLines(sprintf("%-10s: %.2f", "mean", mean(x)))

Output:

template  : The mean nitrate reading is {{m}} across {{n}} samples.
woven     : The mean nitrate reading is 46.25 across 8 samples.
samples   : 8
mean      : 46.25

The template carries placeholders where the numbers belong, and knitting replaces each with a freshly computed value: the mean 46.25 and the count 8 are spliced in, not typed. Change a reading and re-knit, and the woven sentence updates itself. This is the same guarantee as a generated table, applied to a single number in a line of prose -- the sentence cannot fall out of date because it is regenerated every time.


Real World Example: A Parameterised Compliance Section

A water utility knits a compliance report each quarter, and one reusable chunk builds a section for a monitored site: it takes the quarter's readings and the regulatory limit, counts exceedances, computes a pass rate, and weaves a summary sentence. Because the section is generated from the data, a new quarter's numbers flow straight into the words and tables with no retyping. The program below is that chunk's logic, run on one site's readings.

build_section <- function(region, readings, limit) {
  n      <- length(readings)
  exceed <- sum(readings > limit)     # count readings over the limit
  above  <- sum(readings >= limit)    # readings at or above the limit
  within <- sum(readings <= limit)
  rate   <- 100 * within / n
  sentence <- sprintf("%d of %d readings were at or above the %d mg/L limit.",
                      exceed, n, limit)

  writeLines(sprintf("%-17s: %s", "region", region))
  writeLines(sprintf("%-17s: %d", "readings", n))
  writeLines(sprintf("%-17s: %d", "limit", limit))
  writeLines(sprintf("%-17s: %d", "exceed (code >)", exceed))
  writeLines(sprintf("%-17s: %d", "at or above (>=)", above))
  writeLines(sprintf("%-17s: %d", "within limit", within))
  writeLines(sprintf("%-17s: %.1f", "pass rate (%)", rate))
  writeLines(sprintf("%-17s: %s", "report sentence", sentence))
}

build_section("North", c(47, 49, 50, 52, 53, 51, 48, 46), 50)

Output:

region           : North
readings         : 8
limit            : 50
exceed (code >)  : 3
at or above (>=) : 4
within limit     : 5
pass rate (%)    : 62.5
report sentence  : 3 of 8 readings were at or above the 50 mg/L limit.

The chunk does what a good report chunk should: it computes every figure from the readings, so next quarter's data produces next quarter's section automatically, and the woven sentence carries the count and limit without anyone typing them. The pass rate of 62.5 percent and the counts are all derived, and the section would redraw itself on the next knit if a single reading changed. This is reproducibility working as intended -- the words are downstream of the data.

But look carefully at the sentence against the code that fills it. The sentence says three readings "were at or above the 50 mg/L limit," and 3 is the value of exceed. Yet exceed was computed with readings > limit -- strictly greater than 50 -- while "at or above" is the >= count, which is 4. One reading is exactly 50, and it sits precisely in the gap between the two comparisons.

This is the report's real flaw, and it is exactly the kind of error reproducibility does not catch. The document is perfectly reproducible: knit it a thousand times and it says 3 every time, consistently and confidently wrong. The number 3 is the count of readings strictly above the limit, but the sentence describes it as the count at or above, and for a compliance report -- where "the limit" is a legal threshold and a reading of exactly 50 is usually a breach -- that boundary reading has been silently dropped from the headline figure. Reproducibility guarantees the same output from the same input; it guarantees nothing about whether the prose describes the number correctly. A second flaw compounds it: the function's arguments have no defaults and no validation, so a caller who omits limit or passes readings on the wrong scale gets a section that is still reproducible and still wrong. The lesson is that generating prose from data removes transcription errors but not logic errors, and a wrong comparison operator is a logic error that a beautifully reproducible pipeline will faithfully reprint forever.


Common Mistakes

  1. Pasting a computed value into prose instead of weaving it. A number typed into a sentence from a one-off calculation is frozen; the next knit regenerates every chunk around it but leaves the pasted number stale, so the document silently contradicts its own tables. Every figure in the text must come from an inline expression or a chunk.
  1. Editing the knitted output instead of the source. Correcting a typo or a number in the rendered HTML, PDF, or Word file is like inking a fix onto a printed proof: the next knit overwrites it from the source. All changes belong in the source document, never in the rendered artifact.
  1. Leaving heavy computation in the document with no caching. A chunk that refits a slow model or reloads a large file runs in full on every knit, making the report painfully slow to rebuild. Use chunk caching for expensive steps so only changed chunks recompute.
  1. Hiding errors with global warning=FALSE and message=FALSE and forgetting them. Silencing all warnings makes a clean-looking report that may be concealing real problems -- a failed join, a coercion, a package masking. Silence noise per chunk deliberately, not blanket across the document.
  1. Depending on the interactive session's state. A chunk that relies on a variable defined earlier in the console, not in the document, works when you knit from your session and fails when a colleague knits from a clean one. Knit in a fresh session regularly so the document carries everything it needs.
  1. Stamping the run date or other volatile values into the output. Writing the current date, a temporary path, or a random draw without a seed into the report means two knits of the same data produce byte-different files, which defeats any diff-based check that the output is unchanged. Seed random draws and keep volatile values out of reproducible sections.
  1. Confusing eval=FALSE with include=FALSE. eval=FALSE shows the code but does not run it; include=FALSE runs the code but shows nothing. Reaching for the wrong one either displays a listing you meant to hide or silently skips a computation you needed, and the two failures look nothing alike.
  1. Assuming the prose is correct because the numbers are generated. Generating a value from data removes transcription errors, not logic errors. A sentence built around a figure computed with the wrong operator or filter is reproducibly wrong, and the pipeline will reprint it faithfully forever, as the compliance section above shows.
  1. Not parameterising a report that is run repeatedly. Copying a report and editing hardcoded values for each new site or quarter breeds divergent copies that drift apart. Pass the varying values as parameters to one document, so every run shares the same logic and only the inputs change.

Best Practices

  • Treat the source document as the single source of truth, and never touch the rendered output by hand. If something in the output is wrong, the fix goes in the chunk or the prose that produced it, and the correction survives the next knit.
  • Put every number that appears in the text behind an inline expression or a chunk, so no value in the narrative can fall out of step with the data it describes. A report with no hand-typed figures cannot contradict itself.
  • Knit from a clean session before sharing, so the document proves it carries all the data, libraries, and definitions it needs. A report that only knits from your session is not yet reproducible.
  • Set chunk options with intent: hide code with echo=FALSE for a clean report, run-and-hide with include=FALSE for setup, and silence a specific warning only where you understand it. Avoid blanket suppression across the whole document.
  • Cache expensive chunks so a small edit does not trigger a full recompute, and invalidate the cache when the inputs change. Fast rebuilds are what keep a report actually maintained rather than quietly abandoned.
  • Seed any randomness and keep volatile values -- timestamps, temporary paths, machine details -- out of the reproducible body, so the same input always yields the same output and diffs stay meaningful.
  • Parameterise reports that run on a schedule or across many subjects, passing the varying inputs as parameters to one document rather than forking a copy per run. One document, many inputs, is far easier to keep correct.
  • Verify the prose against the code, not just the code against the data. Read each generated sentence beside the expression that fills it, because reproducibility guarantees consistency, not that the words describe the number correctly.

Practice Exercises

  1. Write a short knitr::spin script (using #' for prose and #+ for chunk options) that has a hidden setup chunk, a visible table chunk, and a closing prose line. Knit it and confirm the setup code does not appear while the table output does.
  1. Take a chunk that computes a mean and a count, and write a sentence that weaves both values in with inline expressions. Change one data point, re-knit, and confirm both the table and the woven sentence update together with no manual edits.
  1. Build a table of four chunks with different echo, eval, and include settings, and predict for each whether its code and its output will appear. Knit and check your predictions against what the document actually shows.
  1. Reproduce the compliance-section bug: write a function that counts values with > but describes the count as "at or above" in the sentence, run it on data containing a reading exactly on the limit, and then fix the operator so the number and the words agree.