Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knitr escape latex special characters (e.g., ~, $) in R code

LaTeX crashes when I run it on the output of this knitr document because the LaTeX special characters aren't properly escaped. Any hints how to fix this?

\documentclass{beamer} 
\begin{document}
\begin{frame}{Unescaped dollar signs and tildes}

In this example, neither the tilde nor the dollar sign
will appear in the pdf document, and the dollar sign
will cause a \LaTeX error.

<<xtable, results="asis">>=
n <- 100

x <- rnorm(n)

y <- 2*x + rnorm(n)

out <- lm(y ~ x)

library(xtable)

xtable(summary(out)$coef, digits=c(0, 2, 2, 1, 2))
@

\end{frame}
\end{document}
like image 765
Mark Johnson Avatar asked Oct 20 '22 01:10

Mark Johnson


People also ask

How do you type special characters in R markdown?

5.2 Special characters If you want any special characters in R Markdown, LaTeX, or pandoc to appear as text, rather than having them perform some function, you need to “escape” them with a backslash. For example, pound signs/hashtags, backslashes, and dollar signs need to be preceded by a backslash.

How do you escape in R markdown?

The way to escape a special character is to add a backslash before it, e.g., I do not want \_italic text\_ here . Similarly, if # does not indicate a section heading, you may write \# This is not a heading . As mentioned in Section 4.12, a sequence of whitespaces will be rendered as a single regular space.


1 Answers

You need to add [fragile] option if your frame contains a knitr chunk with special latex characters:

\begin{frame}[fragile]

Source: knitr webpage.

like image 137
tonytonov Avatar answered Oct 24 '22 12:10

tonytonov