R Language R in LaTeX with knitr

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Syntax

  1. <<internal-code-chunk-name, options...>>=
    # R Code Here
    @
  2. \Sexpr{ #R Code Here }
  3. << read-external-R-file >>=
    read_chunk('r-file.R')
    @

    <<external-code-chunk-name, options...>>=
    @

Parameters

OptionDetails
echo(TRUE/FALSE) - whether to include R source code in the output file
message(TRUE/FALSE) - whether to include messages from the R source execution in the output file
warning(TRUE/FALSE) - whether to include warnings from the R source execution in the output file
error(TRUE/FALSE) - whether to include errors from the R source execution in the output file
cache(TRUE/FALSE) - whether to cache the results of the R source execution
fig.width(numeric) - width of the plot generated by the R source execution
fig.height(numeric) - height of the plot generated by the R source execution

Remarks

Knitr is a tool that allows us to interweave natural language (in the form of LaTeX) and source code (in the form of R). In general, the concept of interspersing natural language and source code is called literate programming. Since knitr files contain a mixture of LaTeX (traditionally housed in .tex files) and R (traditionally housed in .R files) a new file extension called R noweb (.Rnw) is required. .Rnw files contain a mixture of LaTeX and R code.

Knitr allows for the generation of statistical reports in PDF format and is a key tool for achieving reproducable research.

Compiling .Rnw files to a PDF is a two step process. First, we need to know how to execute the R code and capture the output in a format that a LaTeX compiler can understand (a process called 'kniting'). We do this using the knitr package. The command for this is shown below, assuming you have installed the knitr package:

Rscript -e "library(knitr); knit('r-noweb-file.Rnw')

This will generate a normal .tex file (called r-noweb.tex in this example) which can then be turned into a PDF file using:

pdflatex r-noweb-file.tex


Got any R Language Question?