Knitr tutorial

knitr is "an engine for dynamic report generation with R. It is a package in the statistical programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents." This page will focus on integrating knitr into LaTeX documents.

Setup
If you are install it locally you need to run R and then install the package within R:

If you are running it from within Overleaf, you just need to make sure that your file is named so that it ends with

Compiling Knitr
On Overleaf, you just hit compile, although it can be tricky to debug and see errors unless you dig into the logs.

On your computer, you can use the Rscript command to just run it from R:

If you use RStudio:


 * Name your file as ".Rnw"
 * Put  as the first line of your file

Using Knitr in RWeb/Sweave mode
There are only really two tricks.

Using Knitr in an inline expression:

Using Knitr in a block:

After this, it's all about options. The most important is  and the default is   but the other critical one is.

Nice to have
I usually use the following preamble:

<>= knit_hooks$set(document = function(x) {  sub('\\usepackage[]{color}', '\\usepackage[usenames,dvipsnames]{color}', x, fixed = TRUE) }) opts_chunk$set(fig.path="figures/knitr-") source("resources/preamble.R") @