# R code (knitr)

Overleaf provides an integration with **knitr**, which allows you to add R code to your LaTeX document to generate a dynamic output.&#x20;

Documents that contain R code must be saved with the extension `.Rtex` or `.Rnw`, otherwise the code won't work. Let's see an example:

```latex
\documentclass{article}
\begin{document}

You can type R commands in your \LaTeX{} document which will be processed and their output included in the document:

<<>>=
# Create a sequence of numbers
X = 2:10

# Display basic statistical measures
summary(X)

@
\end{document}
```

![KnitrDemo1.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2F4rB1ItV9jgLU4dT6o3Hf%2FKnitrDemo1.png?alt=media\&token=5b2d4df8-8de9-4bdd-be61-0a3992026edf)

[ Open this `knitr` example on Overleaf](https://www.overleaf.com/project/new/template/20421?id=69881107\&templateName=Knitr+demo+1\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

As you can see, the text in between the characters `<<>>=` and `@` is R code. This code and its output is printed in a listing-like format. This chunk of code can take some extra parameters to customize the dynamic output, as described in the next section.

## Chunks of code

A code block like the one presented in the previous section is usually called a *chunk*. You can set some extra options in knitr chunks. See the example below:

```latex
\documentclass{article}
\begin{document}

You can type R commands in your \LaTeX{} document which will be processed and their output included in the document:

<<echo=FALSE, cache=TRUE>>=
# Create a sequence of numbers
X = 2:10

# Display basic statistical measures
summary(X)

@
\end{document}
```

![KnitrDemo2.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2FHtobrK1TjY4SG4ax2BH5%2FScreenshot%202025-12-16%20143420.png?alt=media\&token=50675660-f20f-44d3-be60-fb91b8dbd255)

[ Open this `knitr` example on Overleaf](https://www.overleaf.com/project/new/template/20423?id=69885763\&templateName=Knitr+demo+2\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

There are two additional options passed inside `<<` and `>>`.

* `echo=FALSE`This hides the code and only prints the output generated by R.
* `cache=TRUE`If cache is set to true, the chunk is not run, only the objects generated by it. This saves time if the data in that chunk haven't changed.&#x20;

{% hint style="info" %}
*Note that the cache=TRUE option is not currently supported in Overleaf, but it should work locally.*
{% endhint %}

See the [reference guide](https://learn.overleaf.com/learn/Knitr#Reference_guide) for more options.

## Inline commands

It is possible to access objects generated in a chunk and print them in-line.

```latex
\documentclass{article}
\begin{document}

You can type R commands in your \LaTeX{} document which will be processed and their output included in the document:

<<echo=FALSE, cache=TRUE>>=
# Create a sequence of numbers
X = 2:10

# Display basic statistical measures
summary(X)

@

So, the mean of the data is $\Sexpr{mean(X)}$
\end{document}
```

![KnitrDemo3.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2Fbyz9VKDCCPcoWHbznSJ4%2FScreenshot%202025-12-16%20143647.png?alt=media\&token=9d5ef4de-f413-4bf2-83c8-bf2171f50dee)

[ Open this `knitr` example on Overleaf](https://www.overleaf.com/project/new/template/20425?id=69886866\&templateName=Knitr+demo+3\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

The command `\Sexpr{mean(X)}` prints the output returned by the R code `mean(X)`. Inside the braces, any R command can be passed.

## Plots

Plots can also be added to a knitr document, as in this example:

```latex
\documentclass{article}
\begin{document}

<<plot1, fig.pos="t", fig.height=4, fig.width=4, fig.cap="First plot">>=

xdata = read.csv(file="data.txt", head=TRUE,sep=" ")

hist(xdata$data, main="Overleaf histogram", xlab="Data")

@

The figure \ref{fig:plot1} is simple histogram.

\end{document}
```

![KnitrDemo4.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2F5NI4NOJICjnYf8Z2Me1b%2FScreenshot%202025-12-16%20143811.png?alt=media\&token=d937786f-da22-4cbd-9adf-f277ec9f77c4)

[ Open this `knitr` example on Overleaf](https://www.overleaf.com/project/new/template/20427?id=69890965\&templateName=Knitr+demo+3\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=)

This histogram uses data stored in "data.txt", saved in the current working directory. A few figure-related options are passed to the chunk.

`plot1`This is the label used to reference the plot. The prefix "fig:" is mandatory. You can see in the example that the figure is referenced with `\ref{fig:plot1}`.`fig.pos="t"` positioning parameter. This is the same used in [the figure environment](https://learn.overleaf.com/learn/Positioning_images_and_tables#The_figure_environment).`fig.height=4, fig.width=4`Figure width and height.`fig.cap="First plot"`Caption for the figure.

## External R scripts

You can import parts of an external R script into a knitr document. This is very helpful since it is fairly common to write and debug the script in an external program prior to including it in your document.

Suppose we have the following R code in a file called `mycode.R` which we include in our LaTeX document:

```latex
## ---- myrcode1
# Create a sequence of numbers
 X = 2:10

## ---- myrcode2
# Display basic statistical measures
summary(X)
```

Notice the lines:

```latex
## ---- myrcode1
```

and

```latex
## ---- myrcode2
```

These mark the beginning of a chunk of code and are mandatory if you want to use this script in our document, as shown in the following code fragment:

```latex
The chunk below will not be printed

<<echo=FALSE, cache=FALSE>>=
read_chunk("mycode.R")
@

The code must show up here

<<myrcode2>>=

@
```

![KnitrDemo5.png](https://3502988919-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVetOkhFZmAC8QCQK0Pi7%2Fuploads%2FPzKSGsFTMdhs9K8dE8Ny%2FKnitrDemo5.png?alt=media\&token=9c32c381-7621-4b7d-9d73-c1e7a0b6aac8)

The first chunk is not printed and is only used to import the script with the command `read_chunk("mycode.R")` . That's why the option `echo=FALSE` is set. Also, scripts must not be cached. Once the script is imported, you can print a chunk using the label you set after `## ----`. In this case it's `myrcode2`.

We have put all the article code fragments into a project that [ you can Open on Overleaf](https://www.overleaf.com/project/new/template/20429?id=69894649\&templateName=Knitr+full+demo\&latexEngine=pdflatex\&texImage=texlive-full%3A2020.1\&mainFile=) .

## Reference guide

Some chunk options:

* `results`. Changes the behavior of the results generated by the R code. Possible values are:
  * `markup` Use LaTeX to format the output.
  * `asis` Print raw results from R.
  * `hold` Hold the output results and push them to the end of the chunk.
  * `hide` Hide results.
* `echo`. Whether to include the R source code. Other parameters include:&#x20;
  * `echo=2:3` prints only the second and third lines;&#x20;
  * `echo=-2:-3` excludes the second and third lines only.
* `cache`. Whether to cache the code chunk. Possible values are: `TRUE` and `FALSE`
* `highlight`. Whether to highlight the source code. Possible values are: `TRUE` and `FALSE`
* `background`. Background color of the chunk. rgb and HTML formats can be used. The default value is *"#F7F7F7"*.
