Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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). 
like image 691
lowndrul Avatar asked Jun 19 '19 23:06

lowndrul


People also ask

How do I cross-reference from Excel to Word?

Step 1: Copy the excel cell. Step 2: Go to your word document where you want to paste the reference. Step 4: Under paste options, select "link with source formatting" or "link and merge formatting". Thanks.

How do you reference a section in Bookdown?

Authoring Books and Technical Documents with R Markdown In fact, you can also reference sections using the same syntax \@ref(label) , where label is the section ID. By default, Pandoc will generate an ID for all section headers, e.g., a section # Hello World will have an ID hello-world .


Video Answer


1 Answers

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

like image 51
HBat Avatar answered Sep 30 '22 23:09

HBat