[Tex/LaTex] How to render LaTeX (math) in Sweave (R) code comments

commentsmintedrsweave

background

A asked this question on SO yesterday because it seemed to be more programming-oriented, but there weren't any responses. Perhaps someone here might have an idea?

I am writing a Sweave document (LaTeX and R) and I would like to use LaTeX in some R comments. Essentially, I would like to do this:

\documentclass{article}
\begin{document}

Some introduction

<<example>>=

## We will find all $k$ combinations:
## $k = C^n_N = \frac{N!}{(N - n)! \cdot n!}$

k <- factorial(N) / (factorial(N - n) * factorial(n))

@

Some other information.

\end{document}

and have $k$ and $k = C^n_N = \frac{N!}{(N - n)! \cdot n!}$ formatted as they would be if they were not in the R code chunk.

The minted and listings packages both support LaTeX in code comments, but I'm not sure how to combine this with Sweave/knitr. Here is an example from the minted package, page 7:

enter image description here

question

Is there a way to put formatted LaTeX (math) in the comments of a Sweave code chunk?

Best Answer

MWE

Not the comments, that I suggest to hide with echo=F option, but you use here cat or paste to insert a LaTeX chunk inside the R chunks ina LaTeX document to simulate that the R comments is printed in LaTeX, as well as incluging in captions of a xtable , etc. For this you need the option results=tex and taking into account that you need convert all the \ in \\ int the LaTeX text.

\documentclass{article}
\setlength{\parskip}{\bigskipamount}
\setlength{\parindent}{0pt}
\begin{document}
\SweaveOpts{concordance=TRUE}

Some introduction

{\sffamily
<<example,echo=F,results=tex>>=
cat("\\bigskip We will find all $k$ combinations:")
cat("\\[k = C^n_N = \\frac{N!}{(N - n)! \\cdot n!}\\]")

7 -> N
4 -> n
k <- factorial(N) / (factorial(N - n) * factorial(n))

cat("\\[k \\leftarrow factorial(N) / (factorial(N - n) * factorial(n))\\]")

cat("For $N=7$ and $n=4$ is:\\par")

k
@
}

Some other information.

\end{document}

Said that, in general I see little advantages of make this except for chart labels and or some cell table. For comments is a lot easier using plain LaTeX before/after each R chunk, splitting the R code when needed, or make extensive use of the \Sexpr{} to mix LaTeX text with previously calculated values in above chunks (for example, to make automated reports without showing the awful R ouput).