问题描述
我想用 {officedown} 创建一个 .docx
报告,而不是使用“书签”引用类型来交叉引用我在 ch.4.6 和 {{3} 中建议的表格和数字}} 的用户文档中,我希望我的引用是结果 .docx
中实际的“图”和“表”引用类型。如 ch.4.7 中所述,这将需要 {SEQ figure \\* arabic}
和 {SEQ Table \\* arabic}
字字段,答案显示如何通过 officer::slip_in_seqfield()
或 crosstable::body_add_table_legend()
实现。
但是,我认为,这些获取实际“图形”和“表格”引用类型的方法仅适用于 {officer} 语法,而不适用于 {officedown} 语法。说清楚,到目前为止我明白
-
{officer} 语法 作为使用以
dplyr
[this stackoverflow post] 开头的read_docx() %>%
链的 R 脚本 -
{officedown} 语法 作为 Rmd 脚本,在块 [example] 中使用
block_caption()
和run_autonum()
(如有不对请指正)
因此,我想知道是否有一种方法可以修改 {officedown} 中建议的方法,以获得我也可以在文本中交叉引用的实际“图”和“表”引用类型。以下是使用标准建议方法的示例:
You can also make use of the `run_autonum()` and `block_caption()` functions
of the {officer} package. Here are the cross references to Table \@ref(tab:tabmtcars2)
and figure \@ref(fig:figmtcars2). This approach can be used for tables and figures
and the corresponding reference type in MS Word will always be "bookmark".
```{r}
# Table
run_autonum(seq_id = "tab",bkm = "tabmtcars2") %>%
block_caption(autonum = .,label = "mtcars table",style = "Table Caption")
head(mtcars)
# figure
ggplot(head(mtcars),aes(x = mpg,y = hp)) +
geom_point() + theme_bw()
run_autonum(seq_id = "fig",bkm = "figmtcars2") %>%
block_caption(autonum = .,label = "mtcars figure",style = "Image Caption")
```
解决方法
这是我第一次在这里发帖,如果我格式化/等,很抱歉。不正确。但是如果我理解正确的话,官员::run_reference 可能就是你要找的。 Thomas de Marchin 给出了一个非常有用的例子here。
这个的本质是在你的r代码块中使用block_caption和offer::run_autonum,然后在markdown中使用offer::run_reference代替\@ref(tab:some-tab)如下:
```{r}
block_caption(label = 'The Caption',style = 'Table Caption',autonum = officer::run_autonum(seq_id = 'tab',bkm = 'some-tab'))
head(mtcars) %>% flextable()
```
This is a reference to Table `r officer::run_reference('some-tab')`
,
正如您在交叉表的插图 (https://danchaltiel.github.io/crosstable/articles/crosstable-report.html) 中所读到的, 您可以使用以下语法:
---
title: "mtcars"
output: bookdown::word_document2
---
```{r setup,include=FALSE}
library(crosstable)
library(flextable)
library(ggplot2)
```
Table iris is given in Table \@ref(tab:tabmtcars2).
```{r tbl,echo=FALSE,results='asis'}
cat("<caption> (\\#tab:tabmtcars2) Table Iris </caption> \n\r ")
head(mtcars) %>% flextable
```
A figure about mtcars is given in Figure \@ref(fig:tabmtcars).
```{r fig,results='asis'}
cat("<caption> (\\#fig:tabmtcars) Figure of mtcars heard </caption> \n\r ")
ggplot(head(mtcars),aes(x = mpg,y = hp)) +
geom_point() + theme_bw()
```
编号将是正确的,但它不会创建任何 MS Word 字段,因此您将无法将这些书签包含在例如图形摘要中。
我不知道使用 Rmarkdown 包含此类字段的任何方法,但您可以在普通 R 脚本中使用官员语法(在同一链接中描述)。