> For the complete documentation index, see [llms.txt](https://overleaf-pro.ayaka.space/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://overleaf-pro.ayaka.space/latex/more-topics/29-knitr.md).

# Knitr

As noted on Wikipedia, [Knitr is an engine for dynamic report generation with R](https://en.wikipedia.org/wiki/Knitr), a statistics-oriented programming language. This article explains how to add R code to your LaTeX document to generate a dynamic output.

In a standard LaTeX distribution you must have R set up in your operating system and run some special commands to compile it. Overleaf can save you the trouble, **knitr** works out of the box.

## Introduction

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](/files/KG0DMjIxKnQMYUjauxG4)

&#x20;[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 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. See the next section.

## Chunks of code

A code block as 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](/files/uf1jLHc53ldjHOg0Rm2O)

&#x20;[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 three 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. Note that the cache=TRUE option is not currently supported in Overleaf, but it should work locally.

See the [reference guide](#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](/files/LFQB4qteOCEm0K178dSi)

&#x20;[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. See the next 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](/files/poazQVKyl5DCLrc3P3nU)

&#x20;[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.

**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 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](/files/g5S8D6hyORe8fDshpcUv)

The first chunk is not printed, 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 behaviour of the results generated by the R code, possible values are
  * `markup` Use LaTeX for format the output.
  * `asis` Prints raw results from R.
  * `hold` Holds the output results and to push them at the end of the chunk.
  * `hide` Hide results.
* `echo`. Whether to include the R source code. Can take other parameters, `echo=2:3` prints only the second and third lines; `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 colour of the chunk, rgb and HTML formats can be used, the default value is *"#F7F7F7"*.

## Further reading

For more information see

* [Code Highlighting with minted](/latex/formatting/12-code-highlighting-with-minted.md)
* [Using colours in LaTeX](/latex/formatting/13-using-colors-in-latex.md)
* [plots in LaTeX](/latex/field-specific/08-pgfplots-package.md)
* [Inserting Images](/latex/more-topics/27-inserting-images.md)
* [Tables](/latex/figures-and-tables/01-tables.md)
* [Positioning images and tables](/latex/figures-and-tables/02-positioning-images-and-tables.md)
* [TikZ package](/latex/figures-and-tables/05-tikz-package.md)
* [Mathematical expressions](/latex/mathematics/01-mathematical-expressions.md)
* [the **knitr** web page](http://yihui.name/knitr/)
* [the **knitr** package manual](https://bitbucket.org/stat/knitr/downloads/knitr-manual.pdf)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://overleaf-pro.ayaka.space/latex/more-topics/29-knitr.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
