我正在使用RMarkdown为论文创建补充文档。这些补充资料包含许多表格。让我们将这些文件称为补充A和补充B。我希望表格编号反映补充字母,即补充A中第一个表格的表A1或表1A,依此类推。
如何修改表格编号以将字母添加到表格编号模式中?
下面是一个示例,它将生成一个具有正常编号的表:
---
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/)可以创建标题并在代码块之前手动插入它们。如果标题是在代码块中生成的,则将其与Latex包caption
相结合可以删除自动表命名和编号(如何使用xtable或knitr::可操作来抑制.Rmd文件中的自动表名称和编号?(。我已经在带有captionsetup[table]{labelformat=empty}
的YAML中完成了这项工作,但也可以在文档主体中完成。无论哪种方式,标题都可以在代码块中生成,这在我的情况下很重要。
此解决方案停止了预订引用的工作(因为labelformat
不能是empty
(,但在使用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提供替代解决方案。在文档正文的某个位置添加以下内容,以更改默认的图形和表格名称,使其包含字母。
deffigurename{Figure A}
deftablename{Table A}
在将表格标签定义为正常后,在文本使用中引用表格或图形,例如Table A@ref(tab:label)
。
仅此一项就将在表/图标题中留下一个空格(例如,"表A1"而不是"表a 1"(。这可以通过在YAML中添加以下内容来解决:
header-includes:
- usepackage{caption}
- DeclareCaptionLabelFormat{nospace}{#1#2}
- captionsetup[figure]{labelformat=nospace}
- captionsetup[table]{labelformat=nospace}
\DDeclareCaptionLabelFormat创建一个函数(此处标记为nospace
(,该函数在调用时覆盖默认的标题标签。#1
表示分配给表或图形的标签(例如"表A"(,#2
表示表或图形编号。captionsetup
行将所有表和图形的标签格式更改为"nospace"定义的格式。
因此,该代码生成例如"表A1:表名称"作为标题。如果需要,例如"表A-1:表名称",则DeclareCaptionLabelFormat
中的代码应更改为{#1-#2}
。
---
title: "Supplement A"
output: bookdown::pdf_document2
toc: false
header-includes:
- usepackage{caption}
- DeclareCaptionLabelFormat{nospace}{#1#2}
- captionsetup[figure]{labelformat=nospace}
- captionsetup[table]{labelformat=nospace}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
library(bookdown)
```
deffigurename{Figure A}
deftablename{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")
```
答案灵感来自:标题中使用RMarkdown 的图形名称
说明乳胶包装文档:https://ctan.org/pkg/caption