Using RStudio and LaTeX

This post will explain how to integrate RStudio and LaTeX, especially the inclusion of well-formatted tables and nice-looking graphs and figures produced in RStudio and imported to LaTeX. To follow along you will need RStudio, MS Excel and LaTeX.

Using tikzdevice to insert R Graphs into LaTeX

I am a very visual thinker. If I want to understand a concept I usually and subconsciously try to visualise it. Therefore, more my PhD I tried to transport a lot of empirical insights by means of visualization. These range from histograms, or violin plots to show distributions, over bargraphs including error bars to compare means, to interaction- or conditional effects of regression models.

For quite a while it was very tedious to include such graphs in LaTeX documents. I tried several ways, like saving them as pdf and then including them in LaTeX as pdf, or any other file format. Until I found tikzDevice. Tikz is an R Package that translates (almost) any R graph in a LaTeX file which you can easily include in your file. You only have to indicate the file name, as well as the width and height of the graph to get beautiful and publication ready graphs for your LaTeX mannuscript.

Read on to see how it works.

library(tikzDevice) # load the tikzDevice package
library(ggplot2) # load the ggplot2 package
data(mtcars) # load the dataset

# Create the plot
p <- ggplot(data = mtcars, aes(x = cyl, y = mpg)) +
geom_bar(stat = "identity")

# Create the tex file with tikzDevice
tikz(file = 'p_tex.tex', width = 4.5, height = 4.5)
p
dev.off()

Copy this file to the folder in which the LaTeX document you want to include this graph in is. Include the graph with the following lines of code in LaTeX.

\begin{document}
\begin{figure}[h]
    \begin{tabular}{@{}c@{\hspace{.5cm}}c@{}}
        \includegraphics[page=1,width=1\textwidth]{p_tex}
    \end{tabular}
\end{figure}
\end{document}

Using excel2latex and sjPlot to insert R-tables into LaTeX

Here, you first need to install an Excel Plugin (Add-in) called Excel2Latex. Download it here. Just open it anywhere and it should appear under the Add-ins header in Excel. The following example shows how to create a table for regression results with sjPlot.

library(sjPlot) # load the sjPlot package
data(mtcars) # load the dataset

# Create a simple linear model
lm <- lm(mpg ~ cyl, mtcars)

# Create an output table of the linear model with sjstats package
sjt.lm(lm)

Open it in your internet browser, copy it to excel, edit it if you want, and then use excl2latex in order to get the latex code (table or tabular environment).

Related

Next
Previous