Knitr
As noted on Wikipedia, Knitr is an engine for dynamic report generation with R, 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:
\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}
Open this knitr
example on Overleaf
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:
\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}
Open this knitr
example on Overleaf
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 for more options.
Inline commands
It is possible to access objects generated in a chunk and print them in-line.
\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}
Open this knitr
example on Overleaf
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
\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}
Open this knitr
example on Overleaf
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:
## ---- myrcode1
# Create a sequence of numbers
X = 2:10
## ---- myrcode2
# Display basic statistical measures
summary(X)
Notice the lines
## ---- myrcode1
and
## ---- 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:
The chunk below will not be printed
<<echo=FALSE, cache=FALSE>>=
read_chunk("mycode.R")
@
The code must show up here
<<myrcode2>>=
@
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 .
Reference guide
Some chunk options
results
. Changes the behaviour of the results generated by the R code, possible values aremarkup
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 areTRUE
andFALSE
highlight
. Whether to highlight the source code. Possible values areTRUE
andFALSE
background
. Background colour of the chunk, rgb and HTML formats can be used, the default value is "#F7F7F7".
Further reading
For more information see
Overleaf guides
- Creating a document in Overleaf
- Uploading a project
- Copying a project
- Creating a project from a template
- Using the Overleaf project menu
- Including images in Overleaf
- Exporting your work from Overleaf
- Working offline in Overleaf
- Using Track Changes in Overleaf
- Using bibliographies in Overleaf
- Sharing your work with others
- Using the History feature
- Debugging Compilation timeout errors
- How-to guides
- Guide to Overleaf’s premium features
LaTeX Basics
- Creating your first LaTeX document
- Choosing a LaTeX Compiler
- Paragraphs and new lines
- Bold, italics and underlining
- Lists
- Errors
Mathematics
- Mathematical expressions
- Subscripts and superscripts
- Brackets and Parentheses
- Matrices
- Fractions and Binomials
- Aligning equations
- Operators
- Spacing in math mode
- Integrals, sums and limits
- Display style in math mode
- List of Greek letters and math symbols
- Mathematical fonts
- Using the Symbol Palette in Overleaf
Figures and tables
- Inserting Images
- Tables
- Positioning Images and Tables
- Lists of Tables and Figures
- Drawing Diagrams Directly in LaTeX
- TikZ package
References and Citations
- Bibliography management with bibtex
- Bibliography management with natbib
- Bibliography management with biblatex
- Bibtex bibliography styles
- Natbib bibliography styles
- Natbib citation styles
- Biblatex bibliography styles
- Biblatex citation styles
Languages
- Multilingual typesetting on Overleaf using polyglossia and fontspec
- Multilingual typesetting on Overleaf using babel and fontspec
- International language support
- Quotations and quotation marks
- Arabic
- Chinese
- French
- German
- Greek
- Italian
- Japanese
- Korean
- Portuguese
- Russian
- Spanish
Document structure
- Sections and chapters
- Table of contents
- Cross referencing sections, equations and floats
- Indices
- Glossaries
- Nomenclatures
- Management in a large project
- Multi-file LaTeX projects
- Hyperlinks
Formatting
- Lengths in LaTeX
- Headers and footers
- Page numbering
- Paragraph formatting
- Line breaks and blank spaces
- Text alignment
- Page size and margins
- Single sided and double sided documents
- Multiple columns
- Counters
- Code listing
- Code Highlighting with minted
- Using colours in LaTeX
- Footnotes
- Margin notes
Fonts
Presentations
Commands
Field specific
- Theorems and proofs
- Chemistry formulae
- Feynman diagrams
- Molecular orbital diagrams
- Chess notation
- Knitting patterns
- CircuiTikz package
- Pgfplots package
- Typesetting exams in LaTeX
- Knitr
- Attribute Value Matrices
Class files
- Understanding packages and class files
- List of packages and class files
- Writing your own package
- Writing your own class