4.7 Cross-referencing within documents

Cross-referencing is a useful way of directing your readers through your document, and can be automatically done within R Markdown. While this has been explained in Chapter 2 from the bookdown book, we want to present a brief summary below.

To use cross-references, you will need:

  • A bookdown output format: Cross-referencing is not provided directly within the base rmarkdown package, but is provided as an extension in bookdown (Xie 2020c). We must therefore use an output format from bookdown (e.g., html_document2, pdf_document2, and word_document2, etc.) in the YAML output field.

  • A caption to your figure (or table): Figures without a caption will be included directly as images and will therefore not be a numbered figure.

  • A labeled code chunk: This provides the identifier for referencing the figure generated by the chunk.

After these conditions are met, we can make cross-references within the text using the syntax \@ref(type:label), where label is the chunk label and type is the environment being referenced (e.g. tab, fig, or eqn). An example is provided below:

---
title: Cross-referencing figures, tables, and equations
author: Generated by bookdown
output:
  bookdown::html_document2: default
  bookdown::pdf_document2: default
---

See Figure \@ref(fig:cars-plot).

```{r cars-plot, fig.cap="The cars data.", echo=FALSE}
par(mar = c(4, 4, .2, .1))
plot(cars)  # a scatterplot
```

Also see Equation \@ref(eq:mean).

\begin{equation}
\bar{X} = \frac{\sum_{i=1}^n X_i}{n} (\#eq:mean)
\end{equation}

And see Table \@ref(tab:mtcars).

```{r mtcars, echo=FALSE}
knitr::kable(mtcars[1:5, 1:5], caption = "The mtcars data.")
```

The output of this document is shown in Figure 4.2.

Example of cross-referencing within an R Markdown document.

FIGURE 4.2: Example of cross-referencing within an R Markdown document.

You can also cross-reference equations, theorems, and section headers. These types of references are explained further in Section 2.2 and Section 2.6 of the bookdown book.

References

Xie, Yihui. 2020c. Bookdown: Authoring Books and Technical Documents with R Markdown. https://github.com/rstudio/bookdown.