[Rmarkdown, R, bookdown, LaTeX, Dynamic Reports]


Overview

Rmarkdown is an platform for creating dynamic and reproducible reports, journal articles, books, and technical documents with R. Within Rmarkdown it is possible to dynamically reference figures, tables, equations, and sections. Which updates references automatically as your document evolves.

This article introduces the syntax and provides examples to make cross-referencing straightforward and efficient with Rmarkdown.

Tip

For students working on their thesis, consider using the tisemdown thesis template available on our website. It’s a pre-configured Rmarkdown template designed to meet the formatting standards of different study programs, making it the initial setup of your thesis work.

Introduction to Code Chunks

Code chunks in R Markdown, used to execute R code within the document, are defined by three backticks ``` followed by {r}, and they require a chunk name for cross-referencing.

```{r chunk-name}
# R code here

Cross-Referencing Figures

To dynamically reference a figure generated by a code chunk within your document, you need to fullfill a two step procedure:

  1. Assign a label to the chunk.
  • In the case of the example above this is: chunk-name.
  1. Use the syntax Figure \@ref(fig:your-chunk-name) within the markdown part of your document.
  • your-chunk-name is the label you assign to the figure’s code chunk.

This procedure creates dynamic linking in your markdown text to the figures generated from code chunks.

Here is an example which visualizes GDP per capita trends in the Netherlands:

# Your R code Chunk 
 {r visualization-netherlands, 
    fig.cap = "From 1952 to 2007, the GDP per capita in the Netherlands saw a generally steady upward trend. There was a notable exception between 1977 and 1982 when this growth did not follow the usual linear pattern." # Adding a caption
 }

library(ggplot2)
library(dplyr)
library(gapminder)
gapminder %>%
  filter(country == "Netherlands") %>%
  ggplot(aes(x = year,
             y = gdpPercap)) + 
  geom_point()

# Specify this outside the code chunk: in the Markdown part
GDP per capita in the Netherlands is higher than in the last 50 years!
(See Figure \@ref(fig:visualization-netherlands))

Tip

For a full tutorial on Rmarkdown figure formatting. Which discusses chunk and global options, organized saving of figures using the YAML, and LaTeX usage for layout customization. Take a look at this article.

Cross-Referencing Tables

We recommend creating tables from your data frames with the knitr::kable function. kable takes a data.frame as input, and outputs the table into a markdown table, which will be rendered into the appropriate output format.

The same procedure can be applied for referring to tables inside your article:

  1. Assign a label to the chunk.
  2. Use the syntax: Table \@ref(tab:chunk-name) within the markdown part of your document.
  • Again the chunk-name is the label you assign to the table’s code chunk.
# R Code Chunk
## {r table-netherlands, echo = FALSE, warning= FALSE, message = FALSE}
gapminder %>%
  filter(country == "Netherlands") %>%
  head() %>%
  knitr::kable(caption = "Raw gapminder data for the Netherlands", digits = 2)

## Specify this outside the code chunk: in the Markdown
We can see above in Table \@ref(tab:table-netherlands) the raw data used to create Figure \@ref(fig:visualization-netherlands).

Cross-Referencing Sections

To refer to other sections within your document use the syntax: Section \@ref(section-name). Here, section-name corresponds to the unique identifier you assign to a document’s header using the notation {#section-name}.

This procedure creates a link for the reader, allowing him or her to move through different parts of your document efficiently. Making it possible to jup to another section with only a single mouse click.

Assigning Identifiers (Slugs) to Headers

When assigning unique identifiers to headers for referencing purposes, it’s important to append {#unique-id} immediately after the section title in your RMarkdown file.

For example, if you create a Rmarkdown file and create the section # Introduction and label it with the unique identifier {#introduction-section}, it will be now referencable using the syntax Section \@ref(introduction-section)

The full syntax of the header is now: # Introduction {#introduction-section}.

Tip

Unique identifiers, are referred to as slugs. These slugs have one requirement, they should not contain any numbers. This would lead to the identifier being incorrectly displayed as text within the document. For example, while ## Section 4 {#section-4} might seem intuitive, it would not function as intended. Instead, adopt a fully spelled-out format such as ## Section Four {#section-four}.

Cross-Referencing Equations

When reading or writing academic documents, referencing to equations is often considered to be helpful.
To do this, define your equations within an equation environment and assign a unique label using the syntax (\#eq:your_label_here).

Here is an example considering a regression equation:

\begin{equation} 
\operatorname{Sepal.Length} = \alpha + \beta_{1}(\operatorname{Species}_{\operatorname{versicolor}}) + \beta_{2}(\operatorname{Species}_{\operatorname{virginica}}) + \epsilon
  (\#eq:regression-1)
\end{equation} 

This equation can be referred to elsewhere in your document as Equation @ref(eq:regression-1).

Tip

Automate the LaTeX regression equation generation part using the equatiomatic package, discussed in this article.

Advanced Case

For scenarios where multiple lines of an equation should share a single number (e.g. 2.3), use the split environment within an equation. By default, each line in the align environment will be assigned an equation number. In this example, the whole split environment was assigned a single number:

\begin{equation} 
\begin{split}
A &= \int_{0}^{r} 2\pi x \, dx \\
  &= 2\pi \int_{0}^{r} x \, dx \\
  &= 2\pi \left[ \frac{x^2}{2} \right]_{0}^{r} \\
  &= 2\pi \left( \frac{r^2}{2} - 0 \right) \\
  &= \pi r^2
\end{split}
(\#eq:area_circle)
\end{equation}

# Specification in the markdown:
As demonstrated in Equation \@ref(eq:area-circle), the derivation of the area of a circle formula utilizes integral calculus to arrive at the well-known result \(\pi r^2\), where \(r\) is the radius of the circle.

Tip

Best Practice to adopt:

  • Unique Labels: Make sure every figure, table, and section you plan to reference has a unique label or identifier.
  • Descriptive Labels: Use descriptive names for your chunk labels to improve readability and ease of reference.
  • Regular Updates: Continuously knit your document to verify that all references are correctly rendered and linked.
Summary

This article discusses cross-referencing within Rmarkdown for academic writing. Specifically, it guides through:

  • Code Chunks: The syntax for executing R code within an Rmarkdown document. Defined by three backticks followed by {r} and required a chunk name for cross-referencing.
  • Cross-Referencing Figures: Label code chunks and reference in the document with Figure \@ref(fig:chunk-name).
  • Cross-Referencing Tables: Use knitr::kable for table creation. Label and reference tables in the document with Table \@ref(tab:chunk-name).
  • Cross-Referencing Sections: Assign unique identifiers using {slug} to sections and reference them with Section \@ref(section-name).
  • Cross-Referencing Equations: Label equations within an equation environment using (\#eq:label) and reference with Equation \@ref(eq:label).
Contributed by Matthijs ten Tije