lowndrul
lowndrul

Reputation: 3815

Table Cross-References in Bookdown with MS-Word Output?

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). 

Upvotes: 8

Views: 1397

Answers (1)

HBat
HBat

Reputation: 5692

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".

Upvotes: 1

Related Questions