How to combine LaTeX and R for report generation | Towards Data Science

If you have to create a report, LaTeX is definitely the choice to make, everything looks better in LaTeX!
Chances are that you used it to write your thesis or some assays, back in your academia years. Indeed, environments like texstudio or the more recent Overleaf are great for single projects. But now in your day job, can they really scale it up and make LaTeX still useful?
What you need is a method that generates reports automatically (maybe, just there at the end of your pipeline), that changes its content dynamically in relation to the findings of your code, that is visually pleasing (for your boss), and that can be fast enough to mass-produce results.
If that is the case, my favourite solution is the R package “knitr” that allows us to create LaTeX documents directly from R code. Combining the flexibility of a programming language and the LaTeX aesthetics.
In this article, I want to give you a basic tutorial and some tips on how to do it successfully. I understand that not many know both R and LaTeX, I will try to keep it simple, but both coding systems and their combination cannot be explained in one single article, I hope that, if you have clicked on this article and read it until now, you have some basic knowledge on the two.
Without further ado, let’s create a LaTeX report with R.
Two are the steps needed to create a R/tex report, a ‘starter’ R script to create the final pdf, and the .Rnw file where all our code will be stored. Let’s see them:
The ‘starter’ script has to do two basic functions:
Load and pass the Rnw file to the knit command of the knitr package. This process is called weaving. This will execute the R code and produce a series of files among which there’s a .tex file that we would normally use in texstudio.Execute twice the .tex file in order to create the final PDF report
Load and pass the Rnw file to the knit command of the knitr package. This process is called weaving. This will execute the R code and produce a series of files among which there’s a .tex file that we would normally use in texstudio.
Execute twice the .tex file in order to create the final PDF report
To make the overall process easier, I would recommend creating an independent file called starter.R with the code above and run it when needed, with the following command:
R CMD BATCH starter.R
Alternatively, you can copy/paste the three lines of code on the command line or anywhere else you might need.
Don’t forget to install knitr in R.
install.packages('knitr')
The .Rnw (or Sweave) file is in essence a .tex file in which it is possible to insert blocks of R code.
The structure of the file follows the normal structure of a LaTeX work starting with the declaration of the document class but at any point in the code you can add R blocks of code.
Those are defined between two elements: a <<...>> in which the setting of the R code blocks are passed and a @, that defines its end.
Let’s see an example:
So far this is a common code that you could find in any .tex file and it produce the pages in Fig 1. It produce an front page, table of content and the first chapter:
Let’s continue and see the first R block that create a plot with R and import the figure in LaTeX:
In between the less-than and the greater-than signs we can pass the parameters for the execution of our R blocks; the most important elements to pass are:
Name: This is simply the name of the block, each block has to have a unique name. An identify name will help you greatly in the debugging phase
echo: this TRUE or FALSE value will indicate if the code will be shown or not in the final pdf document.
results can take value ‘asis’ or ‘hide’ and it will show or to hide the results (output) of the block
Other parameters are the Boolean “include” that determine if the block has to be run, and “warning” and “message” both determine if the debugging messages have to be shown in the pdf final version.
Let’s see a practical example in which we will load the Iris database and create a plot within the R block of code:
In the code above we define a block of code called CreatePlot , in which we ask to show the underline R code in the pdf but the resulting plot is hidden and iit will be loaded using \includegraphics{}.
In Fig 2 we can see the result of the code above.A title, the block of R code shown as requested with echo and the latex code used to load the figure.
I have manually add the plot in Fig 2 to show the result of the R code, otherwise it will be in a different pdf page.
Let’s see another case using a table as example:
With this block of code, we create a table using the iris database and both the code and the table are immediately shown as you can see below in Fig 3.
We can see that the above block created a table with the Iris database in it (not entirely reported) and the R code that produced it.
For my personal experience the .Rnw file is a very powerful tool, however, I recommend keeping the R code at a minimum, and use the blocks only to import plots and csv/table produced elsewhere. If you prefer to compute and generate content directly in the Rnw it will start to be messy soon.
I hope this article will give a concrete help in the creation of your first report using LaTeX and R.
The full and extended code is present in this GitHub repository:
The above script will produce the following pdf (click on the image within the link).
For more information on knitr: source one and two.
I hope you found this article helpful