R in LaTeX with knitr

Download r eBook

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

Related Examples

Stats

68 Contributors: 1
Monday, September 26, 2016
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook