有时,数据子集不包含任何记录,因此不应生成表。当我想打印满足特定命令的表格时,可能会发生这种情况。 Word 文档对空表的引用是“Table ??”默认情况下。但是,我不想打印此参考资料。
例如markdown文档:
---
title: "Dont show Table reference if no data"
date: "2024-01-09"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
Show this table reference if data exists
## No Data
Find species V in the iris dataset.
```{r iris-v}
iris_v <- iris %>% filter(Species == "V")
```
`r nrow(iris_v)` records of species V exist for iris.
Don't show this table reference because there is no data - avoid **Table ??** being printed.
**Table \@ref(tab:ft-B)**
```{r ft-B}
#Only print flextable if data exists
if(nrow(iris_v) > 0){
flextable::flextable(head(iris_v, 5))
}
```
通过
呈现为Word文档rmarkdown::render(
input = paste0("dont_show_if_no_reference.Rmd"),
output_format = bookdown::word_document2(
number_sections = FALSE, #sections are numbered in template to match header style.
global_numbering = TRUE,
toc = FALSE, #Grading does not have TOC
toc_depth = 4, # DEFAULT Depth of headers to include in table of contents
df_print = "kable",
fig_width = 7, # inches
fig_height = 6, # inches
fig_caption = TRUE,
keep_md = FALSE # verbose #keep the markdown file from knitting
),
clean = TRUE,
quiet = FALSE
)
我认为有条件地在 Rmd 文档中包含此 r 代码可以解决问题:
`r if(nrow(iris) > 0) "**Table \\\@ref(tab:ft-A)**"`
但我收到此错误:
! Failed to parse the inline R code: "**Table \\\@ref(tab:ft-A)**"
Reason: '\@' is an unrecognized escape in character string starting "**Table \\\@"
据我所知,主要原因是缺少flextable的标题(以及转义反斜杠的数量)。
以下是我的例子:
```{r iris-v}
iris_v <- iris %>% filter(Species == "V")
```
`r nrow(iris_v)` records of species V exist for iris.
`r if(nrow(iris_v) > 0) "**Table \\@ref(tab:ft-V)**"`
```{r ft-V}
# Only print flextable if data exists
if(nrow(iris_v) > 0){
flextable::flextable(head(iris_v, 5)) %>%
flextable::set_caption(caption = "")
}
```