在 RMarkdown 中向所有 table 个数字添加一个字母

Adding a letter to all table numbers in RMarkdown

我正在使用 RMarkdown 为论文创建补充文档。这些补充包含许多table。我们将这些文件称为补充 A 和补充 B。我希望 table 编号反映补充字母,即 Table A1 或 Table 1A 用于第一个 table所有 tables.

的补充 A 等等

如何修改 table 编号以将字母添加到 table 编号方案中?

下面是一个示例,它会生成具有正常编号的 table:

---
title: "Supplement A"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
```

```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="MTCars") %>%
  kable_styling(latex_options="hold_position", position="left")
```

使用 captioner 包的不雅解决方案(此处提供了详细信息:https://datascienceplus.com/r-markdown-how-to-number-and-reference-tables/) can create captions and insert them manually just before the code chunk. Combining this with the Latex package caption makes it possible to remove the automatic table naming and numbering if the caption is generated within the code chunk (How to suppress automatic table name and number in an .Rmd file using xtable or knitr::kable?)。我已经在 YAML 中使用 \captionsetup[table]{labelformat=empty} 完成了此操作,但它也可以在文档 body 中完成。无论哪种方式,然后都可以在代码块中生成标题,这对我来说很重要。

此解决方案停止了 bookdown 引用的工作(因为 labelformat 不能是 empty),但是 link 中提供了 table 引用的变通方法以使用captioner 包(包含在下面)。

---
title: "Supplement A"
header-includes:
  - \usepackage{caption}
    \captionsetup[table]{labelformat=empty}
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(captioner)
library(stringr)
```

```{r captions}
# Create the caption(s)
caption <- captioner("Table A", FALSE)
tab_1_cap <- caption("Tab_1", "MTCars")

# Create a function for referring to the tables in text
ref <- function(x) str_extract(x, "[^:]*")
```

The following table is `r ref(tab_1_cap)`.

```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption=tab_1_cap) %>%
  kable_styling(latex_options="hold_position", position="left")
```

可通过 LaTeX 获得替代解决方案。只需在文档正文的某处添加以下内容。

\def\figurename{Figure A}
\def\tablename{Table A}

在将 table 标签定义为正常后,要在文本中引用 table 或图形,例如 Table A\@ref(tab:label)

这也不是一个完美的解决方案,因为它会产生,例如,Table A 1 而不是 Table A1(即带有 space),但它是很多比我之前的解决方案更快更容易。

---
title: "Supplement A"
output: bookdown::pdf_document2
toc: false
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(bookdown)
```

\def\figurename{Figure A}
\def\tablename{Table A}

See Table A\@ref(tab:cars) for something about cars.

(ref:cars) Table caption

```{r cars}
kable(mtcars[1:5, ], booktabs=TRUE, caption="(ref:cars)") %>%
  kable_styling(latex_options="hold_position", position="left")
```

答案灵感来自:Figure name in caption using RMarkdown