introduction to knitr - may sheffield r users group
Post on 07-Aug-2015
180 Views
Preview:
TRANSCRIPT
Dynamic report generation using knitr package
Kate Ren
ScHARR, University of Sheffield
May 19, 2015
Introduction
I knitr is a package writen by Yihui Xie
I generate dynamic documents
I save you time
I reproducible research
What are dynamic documents
I mix source code and documentation together
I 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)
‘‘‘
Tools in R
I Sweave packageI R+LaTeX
I knitr packageI R+LaTexI R+MarkdownI other computing language (e.g. Python, C++, SAS, etc.)
Note:
LaTeX: “a high-quality typesetting system; it includes featuresdesigned for the production of technical and scientificdocumentation.”
Markdown: “a text-to-HTML conversion tool for web writers; itallows to write using an easy-to-read, easy-to-write plain textformat, then convert it to structurally valid XHTML (or HTML).”
knitr
I install.packages(‘‘knitr")
I editors: RStuodio, LyX, etc.
knitr
I in RStudio, change weave Rnw files using Sweave to knitr
knitrI *.Rnw file: LaTeX document with embedded R code (R
Sweave document in RStudio)I *.Rmd file: Markdown document (R Markdown document in
RStudio)I no space in the file names for *.Rnw files, e.g.
Intro-to-knitr.Rnw
An example in LaTeXI � �=: mark the beginning of code chunksI @: terminate a code chunkI \Sexpr { }: embed inline R code
An example in LaTeX
An example in MarkdownI “‘{}: mark the beginning of code chunksI “‘: terminate a code chunkI ‘ ‘: embed inline R codeI ‘: a backtick
An example in Markdown
Chunk options
I syntax almost exactly the same as the syntax for functionaruments in R: option=value
I e.g. echo=TRUEI fig.height=5I results=‘markup’
I can have arbitrary valid R codeI e.g. � foo, eval = if(bar < 5)TRUE else FALSE �=
I chunk label does not have to follow the syntax ruleI e.g. � foo�=I � “foo”�=I � ‘foo′ �=I � label = “foo”�=
I chunk label should have unique id
Chunk options
I echo: TRUE, FALSE
I results: markup, hide, hold, asis
Tables: a LaTeX exampleI Use xtable package
Tables: a Markdown example
Beamer
I Using knitr in beamer slides is similar to LaTeX documnets
I Need to specify fragile option on beamer frames withverbatim output
Other features
I Cache: not re-execute a chunk if it has not been modified
I cross reference: for both code chunks and child documents
I hooks: user-defined R function to fulfill tasks beyond thedefult settings in knitr
Resources
I book by Yihui Xie: Dynamic Documents with R and knitr,Second Edition
I articles about knitr from r-bloggers.com:http://www.r-bloggers.com/search/knitr
I overview of knitr by Yihui Xie from his blog:http://yihui.name/knitr/
top related