为何officedown输出中flextable与data.frame标题及引用样式不同?
问题原因与解决方案
为什么flextable和data.frame的输出被区别对待?
- 当输出是
data.frame时,knitr会调用officedown内置的表格渲染流程:自动应用officedown预设的"Table Caption"样式(包含粗体的"Table X:"前缀),同时将表格编号注册到文档的交叉引用系统中,确保引用编号统一。 - 而
flextable是独立的表格渲染对象,它默认会自行处理标题的生成与样式,不会对接officedown的内置标题样式和交叉引用体系,因此出现前缀非粗体、引用编号不一致的问题。
实现所有图表/表格标题样式统一的方法
方法1:让flextable复用officedown的标题样式(推荐)
使用ftExtra::use_office_caption()函数,让flextable的标题自动继承officedown的"Table Caption"样式,同时对接交叉引用系统:
--- title: "officedown template" output: officedown::rdocx_document --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE, fig.cap = TRUE, echo = FALSE) library(officedown) library(magrittr) library(ftExtra) # 需要额外安装该包
Tables
head(mtcars)
head(iris) %>% flextable::flextable() %>% use_office_caption(caption = "the iris data", style = "Table Caption")
head(cars)
Figures
boxplot(1:8)
barplot(1:8)
Reference
See figure @ref(fig:boxplot) and figure @ref(fig:barplot) and
table @ref(tab:mtcars-data) and table @ref(tab:iris-data) and
table @ref(tab:cars-data)!
### 方法2:手动用officedown的caption函数生成标题 如果不想依赖`ftExtra`,可以先调用`officedown::caption()`生成符合样式的标题,再输出flextable: ```r ```{r tab.id="iris-data", echo=FALSE} # 生成符合officedown样式的标题,自动注册交叉引用 officedown::caption( label = "iris-data", caption = "the iris data", style = "Table Caption" ) # 输出flextable head(iris) %>% flextable::flextable()
### 注意事项 - 方法1需要安装`ftExtra`包,可通过`install.packages("ftExtra")`完成。 - 两种方法都会让flextable的标题前缀变为粗体,同时交叉引用的编号会和其他表格/图表保持一致。 内容的提问来源于stack exchange,提问作者Patrick
相关产品推荐
相关产品推荐

