Template for printing R code in LaTeX
Multiple packages allow formatting programming/markup languages code in LaTeX
. Among them, one of the most widespread is listings. Unfortunately, it does not properly format the R
code, what has generated many questions about how to deal with it and explanations about these problems:
- lstlisting R keywords
- How to nicely display R code with the LaTeX package 'listings'?
- Best use of LaTeX listings package for pretty printing R code
- Colour for R code chunk in listings package
Therefore, I would not recommend using listings
to format R
code in LaTeX
. Further, when there is a better alternative: using Sweave
in combination with the R
library knitr
. How to do it is explained here.
Next, I give a summary with the steps I currently followed:
- In the
LaTeX
file, include theR
code between<<>>=
at the beginning and@
at the end (instead of\begin{listings}
and\end{listings}
), and save this file with theSweave
extension.Rnw
. Right below\begin{document}
, include\SweaveOpts{key1=value1, key2=value2,...,keyn=valuen}
, with your desired default options for theR
code, as for example,echo=TRUE
, etc. - In
R
, execute:
```r
library(knitr)
Sweave2knitr("file.Rnw")
```
applied to your file.
- In the output file
file-knitr.Rnw
ensure that right below\begin{document}
you has
<<include=FALSE, echo=FALSE>>
opts_chunk$set(key1=value1, key2=value2,...,keyn=valuen)
@
Now the default options for the R
code blocks (or chunks) can be those that the library knitr
understands, more than those which Sweave
allows.
- Open this file with RStudio. Open
Tools > Global Options > Sweave
and choose the optionWeave Rnw files using: knitr
(at least withRStudio Version 1.1.463
withWindows 10
). Then, in the main window of RStudio executeCompile PDF
. - Among the output files is the
pdf
, but also the intermediateTeX
file, which one can customize, includingR
code colours, before applying to itpdflatex
.
The other file in this repository is a LaTeX
template with the essential TeX
output of this process, with some explanatory comments added.