8
votes

How can I make table cross-references work in a bookdown document with all of the output formats pdf, docx, and html? Or maybe more specifically, how can I get table cross-references working for flextables?

Below is a minimal working example. The second table, using kable(), gets me almost all the way there. The problem is that the table rendering in docx output is completely unusable (not in this MWE, but in my actual use-case). I considered creating the table conditionally, using flextable for docx output and kable for pdf and html output. flextable looks good in docx output. But the table references don't work!

---
title: "A Book"
author: "Frida Gomam"
site: bookdown::bookdown_site
documentclass: book
output:
  bookdown::word_document2: default
  bookdown::pdf_book: default
  bookdown::gitbook: default
---

# Hello World

```{r setup, include=FALSE}
library(dplyr)
library(flextable)
```

<!--- this tabulates in docx and html output --->
```{r, test01, echo = FALSE, eval = !knitr::is_latex_output()}
mtcars %>%
  head() %>%
  flextable() %>%
  set_caption("My caption!") %>%
  autofit()
```

<!--- this reference does not work in any form of output --->
Trying to reference Table \@ref(tab:test01). 

<!--- this tabulates in pdf, docx, html output (but very ugly in docx output) --->
```{r, test02, echo = FALSE}
mtcars %>%
  head() %>%
  knitr::kable(caption = "Need a caption!")
```

<!--- this reference works in pdf, docx, html output --->
Trying to reference Table \@ref(tab:test02). 
1
The set_caption should have an effect since the new version of flextable (0.5.5 soon on cran). However, bookdown is numbering each table caption (starting with Table: after or before a markdown table) and flextable cannot hook itself to this process (I am working on it but have no solution for now). The same applies to flextable HTML output. I'd like to solve that, if any idea, it will be welcomeDavid Gohel

1 Answers

1
votes

Add tab.cap="Your Caption" to the knitr chunk options:

```{r, test03, echo = FALSE, eval = !knitr::is_latex_output(), tab.cap="My flextable caption!"}
mtcars %>%
  head() %>%
  flextable() %>%
  autofit()
```

Reference to Table \@ref(tab:test03). 

See here for more table caption options.

This also adds numbers to tables correctly. If you want your table captions to be in a format designated in your reference document like "Table Caption" or "Caption", you can specify tab.cap.style = "Table Caption".