Skip to content

Learning Objectives

Main ◇ Understand the structure of an RMarkdown document and how it combines code, output, and narrative text. ◇ Be able to create, knit, and export an RMarkdown report from RStudio. Minor ◇ Know how to control chunk options to show, hide, or suppress code and output. ◇ Be able to use inline R code, tabs, and external script sourcing to organise a report.

Why RMarkdown?

Reproducibility is not an afterthought in science — it is a prerequisite. A common pitfall in data analysis is separating the code from the write-up: figures are copied into a document, numbers are typed manually, and the connection between raw data and final result is broken. Months later, no one can reconstruct exactly how a table was produced or which version of the data was used.

RMarkdown solves this by combining prose, code, and output in a single document. When you knit the file, R executes every code chunk and inserts the results directly into the report. Change the data, re-knit, and every figure, table, and number updates automatically. The result is a document that is not just readable but fully reproducible.

RMarkdown is built on two widely used tools:

  • knitr converts the .Rmd source into plain Markdown by executing the code chunks.
  • Pandoc converts the resulting Markdown into the output format you choose: HTML, PDF, Word, or slides.

RMarkdown and Quarto

You may encounter Quarto (.qmd files) as the newer successor to RMarkdown, introduced by Posit (formerly RStudio) in 2022. Quarto uses the same core concepts — YAML header, prose, and code chunks — and supports R, Python, Julia, and Observable JS in a single framework. Learning RMarkdown gives you a direct foundation for Quarto; switching later requires very little effort. For this course we use RMarkdown because it is fully supported in RStudio and remains the standard in many bioinformatics workflows.


Document Structure

An RMarkdown file (.Rmd) has three components.

YAML Header

The YAML header sits at the top of the file between triple dashes. It controls the document title, author, date, and output format.

---
title: "My Analysis"
author: "Your Name"
date: "`r Sys.Date()`"
output: html_document
---

The backtick expression `r Sys.Date()` is an example of inline R code. It is evaluated at knit time and inserts the current date automatically.

Prose

Outside of code chunks, you write ordinary Markdown: headings with #, bold text with **text**, bullet lists, and so on. This is the narrative layer of your report.

Code Chunks

Code chunks are fenced blocks that begin with three backticks and a language identifier:

```{r chunk-name, option1=TRUE, option2=FALSE}
# R code goes here
summary(iris)
```

The chunk name is optional but strongly recommended. Named chunks are easier to navigate in RStudio and produce predictably named output files. Chunk labels must be unique within a document — using the same label twice causes a Duplicate chunk label error at knit time. Labels are also used internally when naming figure files and cache directories, which is another reason to choose descriptive, unique names.


Chunk Options

Chunk options control what appears in the final output. The most commonly used ones are listed below.

Option Default Effect
eval TRUE Run the code?
echo TRUE Show the source code in the report?
include TRUE Include anything (code and output) in the report?
message TRUE Show messages (e.g. from library())?
warning TRUE Show warnings?
results "markup" How to format text output ("hide" suppresses it)
fig.show "asis" When to show figures ("hide" suppresses them)
fig.width 7 Figure width in inches
fig.height 5 Figure height in inches
fig.cap "" Figure caption
cache FALSE Cache the result and skip re-execution if unchanged?

Two options that beginners often confuse:

Chunk option Code runs? Code shown? Output shown?
echo=FALSE yes no yes
include=FALSE yes no no

include=FALSE suppresses everything — code and output. echo=FALSE runs the chunk and shows the output but hides the source code. Use include=FALSE for setup chunks; use echo=FALSE for figures you want to display without showing the code.

A typical setup chunk at the top of a document sets global defaults:

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

Setting include=FALSE on the setup chunk itself means it runs but produces no output in the report.

Suppressing Package Startup Messages

Loading packages with library() often prints version banners and conflict warnings. Set message=FALSE globally or per chunk to keep your report clean.


Inline R Code

Numbers in prose should be computed, not typed. Use backtick-r notation to embed a value directly in text:

The dataset contains `r nrow(iris)` observations across `r ncol(iris)` variables.

This produces: The dataset contains 150 observations across 5 variables.

If the dataset changes, the sentence updates automatically on the next knit. This is one of the most powerful features of RMarkdown for writing methods sections or results summaries.

Tables

Figures get a lot of attention in reports, but tables are equally common. The simplest way to render a data frame as a formatted table is knitr::kable():

knitr::kable(head(iris), caption = "First six rows of the iris dataset.")

Unlike printing a data frame directly, kable() produces consistently formatted tables across output formats. A raw head(iris) in a chunk renders as plain console output; knitr::kable(head(iris)) renders as a proper table in HTML, PDF, and Word alike.

For more control over formatting — column alignment, cell highlighting, footnotes — the kableExtra package extends kable() substantially. For interactive sortable tables in HTML output, use DT::datatable():

DT::datatable(iris)

Output Formats

The output field in the YAML header determines the final file format. The main options are:

output: html_document      # interactive HTML, easiest to share
output: pdf_document       # requires a LaTeX installation (tinytex)
output: word_document      # editable .docx, useful for collaborators
output: github_document    # plain Markdown for GitHub rendering

For PDF output, install the minimal LaTeX distribution maintained by the RMarkdown team:

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

HTML is the Most Flexible Format

HTML reports can embed interactive figures (e.g. from plotly or DT), handle wide tables gracefully, and are easy to share by email or upload to a server. Unless a PDF or Word file is specifically required, start with HTML.


Knitting a Document

In RStudio, click the Knit button in the toolbar, or press Ctrl+Shift+K (Windows/Linux) or Cmd+Shift+K (macOS). The document is rendered in a separate R session, which means your current environment is not used. Every object the document needs must be created within the document itself.

You can also knit from the R console:

rmarkdown::render("my_analysis.Rmd")
rmarkdown::render("my_analysis.Rmd", output_format = "pdf_document")

Fresh Environment at Knit Time

Because knitting uses a clean R session, code that works interactively may fail during knitting if it depends on objects you loaded manually. Always test by knitting the full document, not just running chunks interactively.


Chunk Execution Order

During knitting, chunks are executed strictly from top to bottom. An object must be created before it is used, regardless of which chunks you ran interactively in RStudio.

A common mistake:

## chunk 2 (appears second in the document)
result * 2          # fails at knit time — result does not exist yet
## chunk 1 (appears first in the document)
result <- 5

Running chunk 2 interactively works if result happens to be in your current environment. Knitting fails because the document is executed in order from the top, in a fresh session where result has not been assigned yet.

The fix is simply to ensure chunk 1 comes before chunk 2 in the document. If you find yourself frequently hitting this problem, it is a sign that the document structure does not reflect the actual analysis order.


Tabs

Tabs are a clean way to present related plots or summaries without cluttering the page. Add {.tabset} to a heading and make the tabs its direct sub-headings:

## Results {.tabset}

### Summary

```{r}
summary(iris)
```

### Scatter plot

```{r}
cols <- c("red", "green", "blue")
plot(iris$Sepal.Length, iris$Petal.Length, col = cols[iris$Species])
```

### Boxplot

```{r}
boxplot(iris$Sepal.Length ~ iris$Species)
```

The three sub-headings become clickable tabs in the HTML output. This works with html_document output; PDF and Word outputs render the tabs as ordinary sections.


External Scripts

For longer analyses it is good practice to keep heavy code in separate R scripts rather than embedding everything in the .Rmd file. There are two distinct ways to work with external scripts, and it is important to understand the difference.

Option 1: Execute an external script

Use source() inside a chunk to execute the script. All objects it creates become available to subsequent chunks, exactly as if the code had been typed there directly.

source("Import.R")

This is the standard way to run a script. The script code is not displayed in the report unless you also set echo=TRUE and inspect the file manually.

Option 2: Display code stored in an external file

The file= option is mainly useful when you want to display code stored in a separate file while still executing it during knitting. In practice, source() is the far more common pattern; file= is relatively rare, but handy when teaching or documenting a pipeline step where showing the exact script contents in the report matters. The script must be in the same working directory as the .Rmd file, or you must provide the full path.

```{r, file='Import.R'}
```

The same file= approach works for shell scripts:

```{bash, file='run_pipeline.sh'}
```

source() vs file=

source("Import.R") executes the file. file='Import.R' displays and executes the file. In most situations they produce the same objects and results in the R session, but only file= makes the code visible in the report. Do not confuse them.


Code Folding

For HTML reports, you can allow readers to show or hide code blocks with a single click. Add code_folding to the YAML header:

---
output:
  html_document:
    code_folding: hide
---

Options are hide (all chunks collapsed by default), show (all expanded), or none (no toggle buttons). This is particularly useful for reports aimed at non-technical readers who want to see results without being distracted by code, but may still want to inspect it.


Table of Contents

A table of contents is generated automatically from the document headings. Add toc to the output options:

---
output:
  html_document:
    toc: true
    toc_float: true
    toc_depth: 3
---

toc_float: true pins the table of contents to the left sidebar so it remains visible as the reader scrolls.


Code Style

Readable code is part of a reproducible report. A consistent style reduces errors and makes it easier for collaborators (and your future self) to understand what each step does. Use sections separated by four or more trailing dashes to create foldable regions in RStudio:

## Data Import ----
otufile <- "ZOTU_c99_Count_Sintax.txt"
mapfile  <- "MapFile.txt"

## Diversity Analysis ----
library(vegan)
d.div <- diversity(otu_table, index = "shannon")

Recommended style references:


Relative Paths

A common source of frustration is a report that knits on your machine but fails on a colleague's. The usual cause is an absolute path:

## Absolute path - breaks on any other machine
read.csv("C:/Users/name/Documents/project/data/samples.csv")
read.csv("/home/name/project/data/samples.csv")

Use relative paths instead, anchored to the location of the .Rmd file:

## Relative path - portable
read.csv("data/samples.csv")

By default, knitting uses the directory containing the .Rmd file as the working directory, not whatever your current RStudio working directory is. Keep data files in a subfolder next to the .Rmd and use relative paths consistently.

For larger projects with more complex directory structures, the here package constructs paths relative to the project root regardless of where the .Rmd file sits:

library(here)
read.csv(here("data", "samples.csv"))

Many bioinformatics workflows eventually migrate to this approach as the project grows.


Challenges

Here is an example RMarkdown document covering most of the concepts on this page.

Download it, open it in RStudio, and knit it before starting the challenges. Read the source alongside the HTML output to see how each feature works in practice.

Challenge 1: Your first RMarkdown document

Open RStudio and create a new RMarkdown document (File > New File > R Markdown). Accept the default template. Knit it to HTML and inspect the output. Identify the three structural components: YAML header, prose, and code chunks.

Solution

The default template produces a short HTML report about the cars dataset. The three components are:

  • YAML header: the block between --- at the top of the file. It contains the title, author, date, and output: html_document.
  • Prose: the plain text outside code chunks, written in Markdown. Includes headings (##), bold text, and regular paragraphs.
  • Code chunks: the fenced blocks beginning with ```{r}. The template includes a setup chunk with include=FALSE, a chunk that loads and summarises cars, and a chunk that produces a scatter plot.

Knitting uses Ctrl+Shift+K (Windows/Linux) or Cmd+Shift+K (macOS), or the Knit button in the RStudio toolbar.

Challenge 2: Add a section with inline R and a captioned figure

Open gda_example.Rmd. Add a new section of your own. Inside it, write one sentence of prose with at least one inline R value, and one code chunk that produces a plot. Add a figure caption using the fig.cap chunk option. Knit and check the result.

Solution

Example addition at the end of the document:

## My Section

The `iris` dataset contains `r nrow(iris)` observations
across `r length(unique(iris$Species))` species.

```{r my-plot, fig.cap="Sepal length by species."}
boxplot(Sepal.Length ~ Species, data = iris,
        xlab = "Species", ylab = "Sepal length (cm)")
```

The inline expressions `r nrow(iris)` and `r length(unique(iris$Species))` are evaluated at knit time and inserted as plain numbers. The fig.cap text appears as a caption below the figure in the HTML output. The chunk label my-plot must be unique within the document.

Challenge 3: Incorporate an existing R script

Take a short R script you have already written (for example, from the terminal or R basics sessions) and incorporate it into an RMarkdown document. You can copy the code directly into chunks, or use source() to execute the script from within a chunk. Use chunk options to suppress messages and warnings. Add at least one inline R value (e.g. the number of rows in a data frame) embedded in a sentence of prose. Knit to HTML.

Solution

Using source() to run an external script silently:

```{r load-data, message=FALSE, warning=FALSE}
source("my_script.R")
```

Alternatively, set these options globally in the setup chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(message = FALSE, warning = FALSE)
source("my_script.R")
```

Embedding an inline value in prose:

After filtering, the dataset contains `r nrow(my_data)` samples.

The key check is to knit the full document with the Knit button, not just run chunks interactively. Objects created by source() are available to all subsequent chunks.

Challenge 4: Create a tabbed report with hidden code

Create a tabbed HTML report using the {.tabset} approach. Include at least three tabs: a summary table, a plot, and a brief interpretation written as prose. Use code_folding: hide so the code is present but collapsed by default.

Solution

YAML header:

---
title: "Tabbed Report"
output:
  html_document:
    code_folding: hide
---

Tab structure:

## Results {.tabset}

### Summary table

```{r summary-table}
knitr::kable(summary(iris), caption = "Summary statistics for the iris dataset.")
```

### Scatter plot

```{r scatter-plot, fig.cap="Sepal vs petal length by species."}
cols <- c("firebrick", "steelblue", "forestgreen")
plot(iris$Sepal.Length, iris$Petal.Length,
     col  = cols[iris$Species],
     pch  = 20,
     xlab = "Sepal length", ylab = "Petal length")
legend("topleft", levels(iris$Species), col = cols, pch = 20)
```

### Interpretation

Petal length increases strongly with sepal length in *Iris virginica*
and *Iris versicolor*, while *Iris setosa* forms a clearly separated
cluster with short petals regardless of sepal length.

With code_folding: hide, all code chunks are collapsed by default. Readers can expand individual chunks by clicking the Code button.

Challenge 5: Add a floating table of contents

Add a floating table of contents to your report from Challenge 4. Adjust the YAML header to include author, date (computed with inline R), and toc_float: true. Knit and verify that the TOC updates correctly when you rename a section heading.

Solution

Updated YAML header:

---
title:  "Tabbed Report"
author: "Your Name"
date:   "`r Sys.Date()`"
output:
  html_document:
    code_folding: hide
    toc:          true
    toc_float:    true
    toc_depth:    3
---

The date expression `r Sys.Date()` is evaluated at knit time. The TOC is built from all Markdown headings up to depth 3. Renaming a heading (e.g. from ## Results to ## Summary) immediately updates the TOC on the next knit. The toc_float: true option pins the TOC to the left sidebar so it remains visible while scrolling.


Additional Information

Useful Chunk Option Patterns

## Run but show nothing at all (e.g. for setup)
```{r, include=FALSE}
```

## Show output but hide source code (e.g. for final figures)
```{r, echo=FALSE}
```

## Show source code but suppress output (e.g. for code review)
```{r, results='hide', fig.show='hide'}
```

## Cache a slow chunk
```{r, cache=TRUE}
```

Session Information

Recording the R version and package versions used is a minimal but important step for reproducibility. Add a session info chunk at the end of every report:

sessionInfo()

For a more structured output that also lists package sources (CRAN, Bioconductor, GitHub):

devtools::session_info()

This takes only one line and makes it possible to reconstruct the exact software environment used to produce the report — something reviewers and future collaborators will appreciate.

Parametrised Reports

RMarkdown supports parameters, allowing you to knit the same document with different inputs. Define parameters in the YAML header and access them via the params list:

---
params:
  sample_id: "C-1"
  min_reads: 1000
---
cat("Processing sample:", params$sample_id, "\n")
reads <- filter(data, n_reads >= params$min_reads)

Knit with different parameters from the console:

rmarkdown::render("report.Rmd", params = list(sample_id = "C-2", min_reads = 500))

This is very useful for generating per-sample reports in a loop.

Child Documents

Large reports can be split across multiple .Rmd files using the child option:

```{r, child='methods.Rmd'}
```

The child document is inserted at that position when knitting. This makes it easier to collaborate on different sections independently.


Additional Resources