Skip to content

iagogv3/R-in-LaTeX

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 

Repository files navigation

R-in-LaTeX

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:

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:

  1. In the LaTeX file, include the R code between <<>>= at the beginning and @ at the end (instead of \begin{listings} and \end{listings}), and save this file with the Sweave extension .Rnw. Right below \begin{document}, include \SweaveOpts{key1=value1, key2=value2,...,keyn=valuen}, with your desired default options for the R code, as for example, echo=TRUE, etc.
  2. In R, execute:
```r
library(knitr)
Sweave2knitr("file.Rnw")
```  

applied to your file.

  1. 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.

  1. Open this file with RStudio. Open Tools > Global Options > Sweave and choose the option Weave Rnw files using: knitr (at least with RStudio Version 1.1.463 with Windows 10). Then, in the main window of RStudio execute Compile PDF.
  2. Among the output files is the pdf, but also the intermediate TeX file, which one can customize, including R code colours, before applying to it pdflatex.

The other file in this repository is a LaTeX template with the essential TeX output of this process, with some explanatory comments added.

About

Template for printing R code in LaTeX

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages