R Language R in LaTeX with knitr R in Latex with Knitr and Code Externalization


Knitr is an R package that allows us to intermingle R code with LaTeX code. One way to achieve this is external code chunks. External code chunks allow us to develop/test R Scripts in an R development environment and then include the results in a report. It is a powerful organizational technique. This approach is demonstrated below.

# r-noweb-file.Rnw
 knitr::opts_chunk$set(echo=FALSE,  cache=TRUE)
This is an Rnw file (R noweb).  It contains a combination of LateX and R.
One we have called the read\_chunk command above we can reference sections of code in the r-file.R script.


When using this approach we keep our code in a separate R file as shown below.

## r-file.R
## note the specific comment style of a single pound sign followed by four dashes

# ---- Chunk1 ----

print("This is R Code in an external file")

x <- seq(1:10)
y <- rev(seq(1:10))