Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace $ with \$; knitr chunk options: echo=TRUE, results='markup;$=\\$'

Tags:

r

knitr

pdflatex

I am trying to print R code within a Latex document using knitr.

I have the following simple code:

  \begin{frame}{Plot Code}
  <<plotcode,eval=FALSE,echo=TRUE,results='markup;$=\\$'>>=

... simple lm from randomly drawn data ...

  yhat.fit <- yhat$fit[,"fit"]

... more simple code ...

 \end{frame}

This will run, BUT, there is no replacement of the $ sign. Instead, I get math mode for fit[,"fit"] in the slide (along with "missing $ inserted" errors from pdflatex compilation.

I would rather not have math mode; instead I would like to see the $ sign, as that is integral to the R code.

As my workaround, I have replaced $ with \$ in my resulting .tex file, but I am hoping someone can fix my seemingly simple problem. I presume I am not specifying the markup and character structure correctly in the options, but I have tried a large number of variations with no success.

like image 826
user3266196 Avatar asked Jan 28 '26 08:01

user3266196


1 Answers

I do not understand what results='markup;$=\\$' really means. The results option does not take such a value; at the moment, it only accepts markup, asis, hide, and hold.

I do not see how $ can be a problem in beamer, either. You probably forgot the fragile option. A minimal example:

\documentclass{beamer}
\begin{document}
\title{A Minimal Demo of knitr}
\author{Yihui Xie}

\maketitle

% very important to use option [fragile] for frames containing code output!

\begin{frame}[fragile]

You can test if \textbf{knitr} works with this minimal demo. OK, let's
get started with some boring random numbers:

<<boring-chunk>>=
fit = lm(dist ~ speed, data = cars)
fit$coefficients
print(sessionInfo(), locale = FALSE)
@

\end{frame}

\end{document}

Output:

knitr with beamer

like image 176
Yihui Xie Avatar answered Jan 30 '26 22:01

Yihui Xie