2. Introduction
knitr is a package writen by Yihui Xie
generate dynamic documents
save you time
reproducible research
3. What are dynamic documents
mix source code and documentation together
computing languages + authoring languages
Here is the plot of the fitted model.
‘‘‘r, ,fig.height=3,fig.width=3, echo=T, results=’hide’
x<-c(1:10)
y<-x+rnorm(10)
par(mar=c(4,4,1,1))
plot(x,y,pch=16)
(lm1<-lm(y x))
abline(lm1)
‘‘‘
4. Tools in R
Sweave package
R+LaTeX
knitr package
R+LaTex
R+Markdown
other computing language (e.g. Python, C++, SAS, etc.)
Note:
LaTeX: “a high-quality typesetting system; it includes features
designed for the production of technical and scientific
documentation.”
Markdown: “a text-to-HTML conversion tool for web writers; it
allows to write using an easy-to-read, easy-to-write plain text
format, then convert it to structurally valid XHTML (or HTML).”
7. knitr
*.Rnw file: LaTeX document with embedded R code (R
Sweave document in RStudio)
*.Rmd file: Markdown document (R Markdown document in
RStudio)
no space in the file names for *.Rnw files, e.g.
Intro-to-knitr.Rnw
8. An example in LaTeX
=: mark the beginning of code chunks
@: terminate a code chunk
Sexpr { }: embed inline R code
12. Chunk options
syntax almost exactly the same as the syntax for function
aruments in R: option=value
e.g. echo=TRUE
fig.height=5
results=‘markup’
can have arbitrary valid R code
e.g. foo, eval = if(bar < 5)TRUE else FALSE =
chunk label does not have to follow the syntax rule
e.g. foo =
“foo” =
‘foo =
label = “foo” =
chunk label should have unique id
16. Beamer
Using knitr in beamer slides is similar to LaTeX documnets
Need to specify fragile option on beamer frames with
verbatim output
17. Other features
Cache: not re-execute a chunk if it has not been modified
cross reference: for both code chunks and child documents
hooks: user-defined R function to fulfill tasks beyond the
defult settings in knitr
18. Resources
book by Yihui Xie: Dynamic Documents with R and knitr,
Second Edition
articles about knitr from r-bloggers.com:
http://www.r-bloggers.com/search/knitr
overview of knitr by Yihui Xie from his blog:
http://yihui.name/knitr/