3
votes

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)."
)
    ```
2

2 Answers

9
votes

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)"
)
```
1
votes

This works for both pdf and html but there might be an easier way.

---
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}
txt <- ifelse(knitr:::is_latex_output(), "\\ref{sec:FirstSection}",     
              "\\@ref(sec:FirstSection)")

knitr::kable(
  cars[1:5, ],
  caption  = paste0("See Section ", txt, ".")
)
```