[Tex/LaTex] Use a LaTeX expression in a knitr figure caption

knitr

I am writing an .Rnw document in RStudio. I would like to be able to use latex expressions in Figure captions created by knitr.

First a code chunk for the caption:

<<cap_4, echo=FALSE>>=
cap <- "My figure. 
Some \textit{italics}. 
A reference to another figure: \ref{fig:other-fig}.
"
@

Now the plot chunk:

<<my-plot, echo=FALSE, fig.cap=cap>>=
ggplot(aes(x = x, y = y), data = data)
@

This fails to correctly render the italics or reference in the figure caption. Instead I get only part of the text (minus the first letter of the expression), e.g. instead of

A reference to another figure: 1.

I get

A reference to another figure: ef{fig:other-fig}.

Is it possible to use latex expressions in a knitr caption?

Best Answer

You need to escape the slash, so that R doesn't treat the \r as a symbol to interpret:

\\ref{fig:other-fig}