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:
question
Is there a way to put formatted LaTeX (math) in the comments of a Sweave code chunk?
Best Answer
Not the comments, that I suggest to hide with
echo=F
option, but you use herecat
orpaste
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 axtable
, etc. For this you need the optionresults=tex
and taking into account that you need convert all the\
in\\
int the LaTeX text.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).