Use a LaTeX expression in a knitr figure caption

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?

• Most likely you need to escape the slash: \\ref{fig:other-fig} Apr 15 '16 at 11:33

1 Answer

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

\\ref{fig:other-fig}