Daniel Krizian
Daniel Krizian

Reputation: 4716

Special character (ampersand) inside LaTeX environment

I have a character vector containing ampersand (&) that displays correctly when used outside LaTeX environment, such as \begin{itemize}.

This works:

---
output:
  pdf_document
---

`r "Guns & Roses"`

The above code runs without error, meaning that either knitr or rmarkdown escapes the ampersand automatically.

Now, when the same R character vector with ampersand is specified inside LaTeX environment, following error is thrown: ! Misplaced alignment tab character &.:

---
output:
  pdf_document
---

\begin{itemize}
\item `r "Guns & Roses"`
\end{itemize}

Upvotes: 3

Views: 19608

Answers (2)

IzzyBizzy
IzzyBizzy

Reputation: 43

I had a similar problem in Rmarkdown, where the Ampersand was supposed to show up in the labels of a ggplot. Using the output hooks CL suggested did not work for me. However, what did help was to put this specific ggplot into its own code chunk (note that I did not escape the ampersand! It is only part of a string variable)– Perhaps a strange workaround for Rmarkdown hickups but seems to work.

Upvotes: -1

CL.
CL.

Reputation: 14957

The reason why the first snippet in the question runs without errors but the second does not is that the & needs to be escaped in LaTeX and pandoc escapes it in the first case but not in the second.

This is because pandoc (with the extension raw_tex) doesn't escape "material between the begin and end tags".

knitr's output hook inline can be used to solve the problem.

One solution—that works for the OP, according to the comments—is to enclose output from R inline expressions in a verbatim environment where the & characer is allowed.

---
output:
  pdf_document
---

```{r, echo = FALSE}
knitr::knit_hooks$set(inline = function(x) {
  return(paste("\\verb|", x, "|"))
})
```

\begin{itemize}
\item `r "Guns & Roses"`
\end{itemize}

Alternatively, the following output hook for inline expressions could be used to replace all & by \&:

knitr::knit_hooks$set(inline = function(x) {
  return(gsub(pattern = "&", 
              replacement = "\\&", 
              x = x, 
              fixed = TRUE))
})

Upvotes: 5

Related Questions