Module 5: Reporting with R Markdown

Write reproducible HTML, PDF, and Word reports that update automatically with your data.

Learning objectives — After this module you will be able to:

  • Explain what reproducible research is and why it matters
  • Create a new R Markdown document in RStudio
  • Write Markdown prose: headers, bold, italic, lists, links, tables
  • Insert and configure code chunks with chunk options
  • Render (knit) to HTML, PDF, and Word output formats
  • Embed ggplot2 figures and formatted tables in a report
  • Use inline R code to insert live values into prose

5.1 What is R Markdown?

R Markdown (.Rmd) files weave together:

  • Prose — written in Markdown
  • Code — in R (or Python, SQL, …) code chunks
  • Output — figures, tables, and printed results

When you click Knit, knitr runs each chunk, collects the output, and pandoc converts everything to a polished document. The result is a report that is always in sync with your data — no copy-pasting figures or numbers.

.Rmd file
    │
    ▼ knitr executes code
    │
Markdown + output
    │
    ▼ pandoc converts
    │
HTML / PDF / Word
Note

Quarto (.qmd) is the next generation of R Markdown, developed by Posit. It supports more output types and languages. The concepts in this module apply to both — .Rmd is still widely used and fully supported.


5.2 Creating Your First R Markdown File

In RStudio:

  1. File → New File → R Markdown…
  2. Enter a title (e.g., "Whale Survey Report") and your name
  3. Choose HTML output (easiest to start with)
  4. Click OK

RStudio creates a template .Rmd file. Read it, then click Knit (or Ctrl+Shift+K) to render it. A browser tab or viewer pane opens with the output.


5.3 The YAML Header

Every .Rmd starts with a YAML block between --- fences:

---
title: "NEAq Survey Report"
subtitle: "Kraus Marine Mammal Conservation Program"
author: "Your Name"
date: "`‌r Sys.Date()`"
output:
  html_document
---

The backtick expression `‌r Sys.Date()` is inline R — it evaluates to today’s date every time you knit.

Output formats

# HTML (most flexible)
output: html_document

# PDF (requires LaTeX — install tinytex first)
output: pdf_document

# Word
output: word_document

# Multiple formats at once
output:
  html_document: default
  pdf_document: default

To install TinyTeX (lightweight LaTeX for PDF output):

install.packages("tinytex")
tinytex::install_tinytex()

5.4 Markdown Syntax

Prose is written in Markdown — a lightweight plain-text formatting language:

# Heading 1
## Heading 2
### Heading 3

Normal paragraph text. Use a blank line to start a new paragraph.

**Bold text**, *italic text*, ***bold and italic***, `inline code`

> This is a blockquote — useful for quoting references.

A [hyperlink](https://cran.r-project.org) and a footnote^[This appears at the bottom].

---     (horizontal rule)

Lists:

- Unordered item
- Another item
  - Nested item (indent with 2 spaces)

1. Ordered item
2. Second item
3. Third item

Tables:

| Species       | Status | Length (m) |
|---------------|--------|-----------|
| Humpback      | LC     | 14        |
| Blue whale    | EN     | 27        |
| Right whale   | CR     | 14        |

5.5 Code Chunks

Code chunks look like this:


::: {.cell}

```{.r .cell-code}
# your R code here
summary(surveys)
```
:::

Key chunk options

Option Default Effect
echo TRUE Show the code in output
eval TRUE Run the code
include TRUE Include chunk output in document
message TRUE Show messages (e.g., package loading)
warning TRUE Show warnings
fig.width 7 Figure width in inches
fig.height 5 Figure height in inches
fig.cap "" Figure caption
cache FALSE Cache results (speeds up re-knit)
results 'markup' 'hide' suppresses printed output

Setup chunk (always the first chunk)

{r setup, include = TRUE}
knitr::opts_chunk$set(
  echo    = TRUE,
  message = FALSE,
  warning = FALSE,
  fig.width  = 7,
  fig.height = 4.5
)

library(tidyverse)
library(janitor)
library(lubridate)
library(knitr)

5.6 A Complete Report Example

Below is a full .Rmd report that brings together everything from this module — a setup chunk, inline R values, a map, and formatted tables.

⬇ Download example_survey_report.rmd

Save it into your project folder alongside your .Rproj file and knit it with Ctrl+Shift+K. It expects the three processed .rds files produced in Module 3 to be in data/processed/.

The report demonstrates:

  • A setup chunk that loads packages, reads data, and pre-computes summaries so all later chunks stay short and readable
  • Inline R to weave live values (date, duration, sighting counts) directly into prose — change the data and the text updates automatically on re-knit
  • A map chunk using ggplot2 + sf + rnaturalearth to plot the survey track and sighting locations
  • kable() tables for the sightings tally, right whale records, and effort summary —

5.7 Inline R Code

Inline code lets you embed computed values directly in your prose — the values update automatically when data changes:


The New England Aquarium conducted a survey aboard the vessel *R/V Nereid* on `‌r format(track_summary$date, '%b %d %Y')`. We left the dock at `‌r format(track_summary$start_time, '%H:%M %p')` and returned at `‌r format(track_summary$end_time, '%H:%M %p %Z')` (approximately `‌r round(track_summary$duration_hrs,1)` hours), during which time we covered approximately `‌r track_summary$total_dist_nm` nautical miles. Sea state ranged from `‌r min(environmental$beaufort)` to `‌r max(environmental$beaufort)`. We recorded `‌r sum(sightings_summary$n_sightings)` sightings of `‌r nrow(sightings_summary)` species, including `‌r nrow(rw_sightings)` right whale sightings. See below for more details.

This eliminates the error-prone step of manually updating numbers in a report when data changes.


5.8 Tables

knitr::kable()

sightings_summary |>
  kable(
    col.names = c("Species Code", "Sightings Events", "Number of Individuals", "Number of Calves"),
    caption   = "Summary of sightings by species",
    align     = c("l", "r", "r")
  )

Check out the kableExtra library for more table style options.

🎉 Congratulations!

You’ve completed all five modules of R for Marine Scientists. You can now:

  • Navigate RStudio and write R scripts
  • Manipulate data with tidyverse verbs
  • Build publication-quality visualisations with ggplot2
  • Write reproducible, parameterised reports with R Markdown

Where to go next:

Resource URL
R for Data Science (free book) https://r4ds.hadley.nz
ggplot2 extensions gallery https://exts.ggplot2.tidyverse.org
Posit Cheatsheets https://posit.co/resources/cheatsheets/