Skip to content

We recommend the listings package for including R code in LaTeX documents. If you add

\usepackage{listings}

to your preamble, you can then insert R code as demonstrated in this example:

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=R]
fib <- function(n) {
  if (n < 2)
    n
  else
    fib(n - 1) + fib(n - 2)
}
fib(10) # => 55
\end{lstlisting}
\end{document}

 Open this example in Overleaf

This example produces the following output:

R code typeset in LaTeX on Overleaf

Our article on using Knitr may also be of interest.

Overleaf guides

LaTeX Basics

Mathematics

Figures and tables

References and Citations

Languages

Document structure

Formatting

Fonts

Presentations

Commands

Field specific

Class files

Advanced TeX/LaTeX