如何在适用于 pdf 和 html 输出的簿记文档中的 table 标题中插入引用

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

我使用 bookdown 生成 html 和 pdf 格式的文档。我如何在 table 的标题中插入对文档部分的引用?

使用 \ref{sec:FirstSection} 适用于 pdf_book (但不是 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}."
)
```

虽然使用 \@ref(sec:FirstSection) 在 gitbook 上工作正常(但不是 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)."
)
    ```

这对 pdf 和 html 都适用,但可能还有更简单的方法。

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

您可以使用 text referencesbookdown 提供的 Markdown 扩展。

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