Search code examples
r-markdowncaptioncross-referencebookdown

How to insert a reference in a table caption in a bookdown document that works for both pdf and html output


I use bookdown to generate a document in both html and pdf. How could I insert a reference to a section of the document in the caption of a table?

Using \\ref{sec:FirstSection} works fine with pdf_book (but not gitbook):

---
title: "Test"
output: bookdown::pdf_book
---

# A section {#sec:FirstSection}
The dataset in Table \@ref(tab:aTable) contains some data.

# Another section
```{r, aTable, echo = FALSE}
knitr::kable(
  cars[1:5, ],
  caption  = "See Section \\ref{sec:FirstSection}."
)
```

whilst using \\@ref(sec:FirstSection) works fine with gitbook (but not pdf_book)

---
title: "Test"
output: bookdown::gitbook
---

# A section {#sec:FirstSection}
The dataset in Table \@ref(tab:aTable) contains some data.

# Another section
```{r, aTable, echo = FALSE}
knitr::kable(
  cars[1:5, ],
  caption  = "See Section \\@ref(sec:FirstSection)."
)
    ```

Solution

  • You can use text references, a Markdown extension provided by bookdown.

    ---
    title: "Test"
    output: bookdown::gitbook
    ---
    
    # A section {#sec:FirstSection}
    
    The dataset in Table \@ref(tab:aTable) contains some data.
    
    # Another section
    
    (ref:aTable-caption) See Section \@ref(sec:FirstSection).
    
    ```{r, aTable, echo = FALSE}
    knitr::kable(
      cars[1:5, ],
      caption  = "(ref:aTable-caption)"
    )
    ```