rr-markdownbookdown

RMarkdown: not include a table cross reference in document if no data


Sometimes, a subset of data contains no records, so a table shouldn't be generated. This may occur in a situation where I want to print a table that satisfies a specific command. A Word document reference to an empty table is "Table ??" by default. However, I don't want to print this reference out.

For example, the markdown document:

---
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))
}
```

is rendered to a word document via

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
)

The word document is shown here:enter image description here

I'm thinking that including this r code conditionally in Rmd document would do the trick:

`r if(nrow(iris) > 0) "**Table \\\@ref(tab:ft-A)**"`

But I get this error:

! Failed to parse the inline R code: "**Table \\\@ref(tab:ft-A)**"
Reason: '\@' is an unrecognized escape in character string starting "**Table \\\@"

Solution

  • As far as I see, the main reason is the lack of flextable's caption (and number of escape backslash).

    Below is my example:

    ```{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 = "")
    }
    ```