R Markdown 中 HTML 输出的 Auto-Numbering 图和 Table 标题

Auto-Numbering of Figure and Table Captions for HTML Output in R Markdown

当我将 R Markdown 文档编织成 HTML 格式时,有没有办法自动为标题中的数字编号?

我希望输出如下:

Figure 1: Here is my caption for this amazing graph.

但是,我目前得到以下信息:

Here is my caption for this amazing graph.

这是我的 MWE:

---
title: "My title"
author: "Me"
output: 
  html_document:
  number_sections: TRUE
  fig_caption: TRUE
---

```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```

```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```

```{r table1, fig.cap="Here is my caption for an amazing table."}
head(mtcars, 2)
```

我已了解到此问题已通过 Bookdown 解决,但我已经阅读了 Bookdown 权威指南,从头到尾都找不到它。

如果您希望有数字编号,您将需要使用 bookdown 提供的输出格式。其中包括 html_document2pdf_document2 等。有关更全面的选项列表,请参阅 here

将您的文档示例 html_document 更改为 bookdown::html_document2 将解决您的问题。

---
title: "My title"
author: "Me"
output: 
  bookdown::html_document2:
  number_sections: TRUE
  fig_caption: TRUE
---

```{r setup}
knitr::opts_chunk$set(echo=FALSE)
```

```{r plot1,fig.cap="Here is my caption for this amazing graph."}
x <- 1:10
y <- rnorm(10)
plot(x,y)
```

```{r plot2, fig.cap="Here is my caption for another amazing graph."}
plot(y,x)
```

如果您想标记由 knitr::kable 创建的 table,您将需要在 table 调用自身

中指定标题
```{r table1}
knitr::kable(mtcars[1:5, 1:5], caption = "Here is an amazing table")
```