reproducible documents/analytics in R: the knitr package

When I am working in new institutions and I am asking: “Do you have a document management system?” I often get the answer:”Yap, we are using folders” … OKAY. Making analysis, developing applications and keeping an eye on code, data and applications make this even harder as it has to be.
Of course not many institutions are using R and Latex but there is a nice little package called knitr which tries to make this a little bit easier. It combines your analysis and documentation in one single document aka PDF.



I would like to show you a little example:


install.packages("knitr")
library("knitr")

this will install knitr in R. So lets go straight ahead with an easy example. What you will write is a so called *.Rnw file. This will have the same structure as a tex-file but it will contain R code as well. But prior document creation keep an eye on your settings: In Rstudio you will find an easy dialogue which will control the knitr behaviour:

Rstudio preferences for knitr/Sweave (click to enlarge)

And if you use something like a default working directory check your default working directory in Rstudio as well as it differs from the one you had set using setwd(“path”):

default path setting in Rstudio (click to enlarge)

So lets come to the *.Rnw file:


documentclass{article}
begin{document}
title{minimal knitr example in R}
author{R. Klinger}
maketitle
this is our workflow:
<<>>=
set.seed(99)
x = 1 + rnorm(200,3,2)
mean(x);var(x)
@
the first two elements of x are Sexpr{x[1:2]}

<<echo=FALSE>>=
plot(x, main="daily returns of asset X", ylab="returns", xlab="days")
abline(lm(x ~ seq(1,200,1)))
@
end{document}

Between the “<<>>=” and the “@” you can put your R code. referencing in line using data from R works in our example with Sexpr{x[1:2]} which will type the first two elements of x in your document directly into one line. If you don’t want code to appear on your PDF you can adjust the “echo” option.
So how to get a document out of it? Store the above code as an *.Rnw file in your working directory, load it into RStudio and press “Compile PDF” or just watch this video:

Isn’t this a cool way to document your work???

Published by Riccardo

In 2008 I finished my degree in geography and mathematics at the FU Berlin in Berlin. After a short stay in science as a research assistant I am a project manager in the geo-industry.

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jas Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
newest oldest most voted
Notify of
Jas
Guest
Jas

Thanks, this has started me into knitr.