为什么 R Markdown Caption 不能带“&”

问题描述

我正在逐步构建 R Markdown (.RMD) 文件,边做边学。我能够插入几个表,但其中一个有问题。初始设置是:

---
title: "Untitled"
author: "Me"
date: "5/10/2021"
output: bookdown::pdf_book
---

```{r setup,include=FALSE}
library(knitr)
opts_chunk$set(echo = FALSE,fig_align = "left",fig_width = 7,fig_height = 7,dev = "png",cache = FALSE)
```

产生错误的原始代码

```{r sphistperf}
kable(stock_index_stats,format="latex",caption="S&P Historical Performance Statistics")
```

错误信息是:

output file: TestCenter.knit.md

! Misplaced alignment tab character &.
<argument> ...}{\relax }}\label {tab:sphistperf}S&
                                                  P Historical Performance S...
l.202 ...rf}S&P Historical Performance Statistics}

Error: LaTeX Failed to compile TestCenter.tex. See https://yihui.org/tinytex/r/#debugging for debugging tips. See TestCenter.log for more info.
Error during wrapup: 
Error: no more error handlers available (recursive errors?); invoking 'abort' restart

如果我从标题删除“&”,问题就解决了,它变成

caption="SP Historical Performance Statistics"

不过,我还是想要标题中的“&”。有没有办法保留它?我尝试在它前面放一个转义字符“”,但没有用。关于如何保留“&”的任何建议?

解决方法

根据wiki,有些字符需要转义

enter image description here


这里是经过测试的markdown代码

---
title: "testing"
author: "akrun"
date: "10/05/2021"
output: bookdown::pdf_book
---

```{r setup,include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r cars}
library(kableExtra)
kable(summary(cars),format = 'latex',caption="Dummy S\\&P Performance")
```

-输出

enter image description here