Including % symbol in table caption of bookdown latex table

Viewed 114

I am having trouble including the '%' symbol in the caption of a table produced by the knitr::kable function in a bookdown Rmarkdown document. For example, the following code:

---
title: "Test of table caption with percent symbol"
output: 
  bookdown::pdf_document2: default
  pdf_document: default
---

```{r}
df = data.frame(id=1:3,names=letters[1:3])

knitr::kable(df,caption="This captions has a % symbol",booktabs=TRUE)
```

produces the following:

enter image description here

However, if I remove the '%' symbol from the caption or I use pdf_document instead of bookdown::pdf_document2 then the output is formatted correctly.

What is the best solution to be able to include '%' and other symbols special to LaTeX in the figure caption? Also, I need a solution that works for multiple output formats (e.g., DOC and HTML in addition to PDF).

1 Answers

I found two solutions to my own question. One is to use a caption reference:

---
title: "Test of table caption with percent symbol"
output: 
  bookdown::pdf_document2: default
  pdf_document: default
---

(ref:mycap) This captions has a % symbol

```{r}
df = data.frame(id=1:3,names=letters[1:3])

knitr::kable(df,caption="(ref:mycap)",booktabs=TRUE)
```

The other is to set format="pandoc" in knitr::kable:

---
title: "Test of table caption with percent symbol"
output: 
  bookdown::word_document2: default
  bookdown::pdf_document2: default
  pdf_document: default
---

```{r}
df = data.frame(id=1:3,names=letters[1:3])

knitr::kable(df,caption="This captions has a % symbol",booktabs=TRUE,format="pandoc")
```

These solutions produce somewhat different table placements on the page and the caption reference solution will not work if one switches from bookdown::pdf_document2 to pdf_document, but otherwise the output is the same.

Related