如何在适用于pdf和html输出的bookdown文档中的表格标题中插入引用

时间:2017-10-10 15:22:29

标签: r-markdown caption cross-reference bookdown

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

使用\\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)."
)
    ```

2 个答案:

答案 0 :(得分:4)

您可以使用text references bookdown 提供的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)"
)
```

答案 1 :(得分:0)

这适用于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, ".")
)
```