6 Cross-referencing

Cross-referencing lets you refer to figures and tables in your document. Once set up, this happens automatically, so you don’t need to re-number all the figures when you add or delete one.

Cross-referencing needs to use a bookdown package output, declared in the YAML.

---
title: "My Manuscript"
output: bookdown::html_document2
---

6.1 Cross-referencing figures and tables

The chunk that made the figure or table needs to have a label (no underscores!) and a caption.

```{r}
#| label: penguin-dens
#| fig-cap = Histogram of penguin body mass
penguins |> 
  ggplot(aes(x = flipper_length_mm, fill = species)) +
  geom_density(alpha = 0.7) +
  scale_fill_brewer(palette = "Set1")
```
Boxplot of penguin body mass

Figure 6.1: Boxplot of penguin body mass

To cross-reference the figure made by the above chunk, we need to use this notation.

Penguins are cool (Fig. \@ref(fig:penguin-dens))

Penguins are cool (Fig. 6.1)

To refer to a table made by a chunk called penguin-results, you would use

Penguins are cool (Table \@ref(tab:penguin-results))

Note that the fig has been replaced by tab in the reference.

If you get the chunk name wrong, there will be a warning when the document in knitted, and question marks shown where the reference should be.

Figure \@ref(fig:no-exist)) does not exist

Non-existing figure (Fig. ??)

6.2 Cross-referencing equations

To cross-reference an equation, we need to give it a label.

$$
\frac{\sum_{i=1}^{n}{x_i}}{n}
 (\#eq:mean)
$$

Note that the equation must be on the line below the dollars. RStudio will try to show the label in the preview - ignore it. Now the label can be used.

The mean (equation \@ref(eq:mean)).

\[ \frac{\sum_{i=1}^{n}{x_i}}{n} \tag{6.1} \]

The mean (equation (6.1)).

6.3 Cross-referencing document sections

You can also refer to other sections of the document using the title/subtitle. For example, to refer to this section, you would use

Cross-referencing (Section \@ref(cross-referencing-document-sections))

Cross-referencing (Section 6.3)

Note that the reference must be written in lower case and spaces must be replaced by hyphens. Punctuation is deleted.