An introduction to knitr and R Markdown

An Introduction to knitr and RMarkdown
https://github.com/sahirbhatnagar/knitr-tutorial
Sahir Bhatnagar
August 12, 2015
McGill Univeristy
Acknowledgements
• Toby, Matthieu, Vaughn,
Ary
• Maxime Turgeon (Windows)
• Kevin McGregor (Mac)
• Greg Voisin
• Don Knuth (TEX)
• Friedrich Leisch (Sweave)
• Yihui Xie (knitr)
• John Gruber (Markdown)
• John MacFarlane (Pandoc)
• You
2/36
Disclaimer #1
I don’t work for, nor am I an author of any of these packages. I’m just a
messenger. 3/36
Disclaimer #2
• Material for this tutorial comes from many sources. For a complete
list see: https://github.com/sahirbhatnagar/knitr-tutorial
• Alot of the content in these slides are based on these two books
4/36
Objectives for today
• Create a reproducible
document (pdf, html)
5/36
Objectives for today
• Create a reproducible
document (pdf, html)
5/36
C’est parti
6/36
What?
What is needed for Reproducible research?
code
data
text
8/36
Why?
Why should we care about RR?
For Science
Standard to judge
scientific claims
Avoid duplication
Cumulative
knowledge
development
Why should we care about RR?
For Science
Standard to judge
scientific claims
Avoid duplication
Cumulative
knowledge
development
For You
Better work
habits
Better teamwork
Changes
are easier
Higher re-
search impact
10/36
001-motivating-example
A Motivating Example
Demonstrate: 001-motivating-example
12/36
How?
Tools for Reproducible Research
Free and Open Source Software
• RStudio: Creating, managing, compiling documents
• LATEX: Markup language for typesetting a pdf
• Markdown: Markup language for typesetting an html
• R: Statistical analysis language
• knitr: Integrate LATEXand R code. Based on Prof. Friedrich Leisch’s
Sweave
14/36
knitr
What knitr does
LATEX example:
Report.Rnw (contains both
code and LaTeX)
Report.tex
knitr::knit(’Report.Rnw’)
What knitr does
LATEX example:
Report.Rnw (contains both
code and LaTeX)
Report.tex
knitr::knit(’Report.Rnw’)
Report.pdf
latex2pdf(’Report.tex’)
16/36
Compiling a .Rnw document
The two steps on previous slide can be executed in one com-
mand:
knitr::knit2pdf()
or in RStudio:
17/36
Incorporating R code
• Insert R code in a Code Chunk starting with
<< >>=
and ending with
@
In RStudio:
18/36
Example 1: Show code and results
<<example-code-chunk-name, echo=TRUE>>=
x <- rnorm(50)
mean(x)
@
produces
x <- rnorm(50)
mean(x)
## [1] 0.031
19/36
Example 2: Tidy code
<<example-code-chunk-name2, echo=TRUE, tidy=TRUE>>=
for(i in 1:5){ print(i+3)}
@
produces
for (i in 1:5) {
print(i + 3)
}
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
20/36
Example 2.2: don’t show code
<<example-code-chunk-name3, echo=FALSE>>=
for(i in 1:5){ print(i+3)}
@
produces
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
21/36
Example 2.3: don’t evaluate and don’t show the code
<<example-code-chunk-name4, echo=FALSE, eval=FALSE>>=
for(i in 1:5){ print(i+3)}
@
produces
22/36
R output within the text
• Include R output within the text
• We can do that with“S-expressions”using the command
Sexpr{. . .}
Example:
The iris dataset has Sexpr{nrow(iris)} rows and
Sexpr{ncol(iris)} columns
produces
The iris dataset has 150 rows and 5 columns
23/36
Include a Figure
<<fig.ex, fig.cap='Linear Regression',fig.height=3,fig.width=3>>=
plot(mtcars[ , c('disp','mpg')])
fit <- lm(mpg ~ disp , data = mtcars)
abline(fit,lwd=2)
@
qqq q
qq
q
qq
qq qq
q
qq
q
q
q
q
q
qq q
q
q q
q
q
q
q
q
100 200 300 400
1025
disp
mpg
Figure 1: Linear regression
24/36
Include a Table
<<table.ex, results='asis'>>=
library(xtable)
tab <- xtable(iris[1:5,1:5],caption='Sample of Iris data')
print(tab, include.rownames=FALSE)
@
library(xtable)
tab <- xtable(iris[1:5,1:5], caption = 'Sample of Iris data')
print(tab, include.rownames = F)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
5.10 3.50 1.40 0.20 setosa
4.90 3.00 1.40 0.20 setosa
4.70 3.20 1.30 0.20 setosa
4.60 3.10 1.50 0.20 setosa
5.00 3.60 1.40 0.20 setosa
Table 1: Sample of Iris data
25/36
RMarkdown
Markdown: HTML without knowing HTML
27/36
R + Markdown = RMarkdown
28/36
What rmarkdown does
RMarkdown example:
Report.Rmd (contains both
code and markdown)
Report.md
knitr::knit(’Report.Rmd’)
What rmarkdown does
RMarkdown example:
Report.Rmd (contains both
code and markdown)
Report.md
knitr::knit(’Report.Rmd’)
Report.html,
Report.pdf,
Report.doc
pandoc
29/36
Compiling a .Rmd document
The two steps on previous slide can be executed in one com-
mand:
rmarkdown::render()
or in RStudio:
30/36
Final Remarks
How to choose between LATEX and Markdown ?
math/stat symbols tecccccc
beamer presentations teccccc
customized documents tecccc
publish to journals, arXiv
quick and easy reportstkkk
use javascript libraries tekkt
interactive plots texkkkkjjt
publish to websites
LATEX
Markdown
32/36
33/36
Always Remember ...
Reproducibility ∝
1
copy paste
34/36
Is the juice worth the squeeze?
35/36
Session Info
• R version 3.2.1 (2015-06-18), x86_64-pc-linux-gnu
• Base packages: base, datasets, graphics, grDevices, methods, stats,
utils
• Other packages: data.table 1.9.4, dplyr 0.4.1, ggplot2 1.0.1,
knitr 1.10.5, xtable 1.7-4
• Loaded via a namespace (and not attached): assertthat 0.1,
chron 2.3-45, colorspace 1.2-6, DBI 0.3.1, digest 0.6.8, evaluate 0.7,
formatR 1.2, grid 3.2.1, gtable 0.1.2, highr 0.5, magrittr 1.5,
MASS 7.3-43, munsell 0.4.2, parallel 3.2.1, plyr 1.8.3, proto 0.3-10,
Rcpp 0.12.0, reshape2 1.4.1, scales 0.2.5, stringi 0.5-5, stringr 1.0.0,
tools 3.2.1
Slides made with Beamer mtheme
36/36
1 of 40

Recommended

R Markdown Tutorial For Beginners by
R Markdown Tutorial For BeginnersR Markdown Tutorial For Beginners
R Markdown Tutorial For BeginnersRsquared Academy
6.8K views30 slides
Introduction to R by
Introduction to RIntroduction to R
Introduction to RKazuki Yoshida
6.8K views52 slides
R Programming: Introduction to Matrices by
R Programming: Introduction to MatricesR Programming: Introduction to Matrices
R Programming: Introduction to MatricesRsquared Academy
2.9K views42 slides
Data Types and Structures in R by
Data Types and Structures in RData Types and Structures in R
Data Types and Structures in RRupak Roy
148 views14 slides
Introduction to R Programming by
Introduction to R ProgrammingIntroduction to R Programming
Introduction to R Programmingizahn
8.2K views71 slides
Introduction to Rstudio by
Introduction to RstudioIntroduction to Rstudio
Introduction to RstudioOlga Scrivner
3K views24 slides

More Related Content

What's hot

Data Redundancy & Update Anomalies by
Data Redundancy & Update AnomaliesData Redundancy & Update Anomalies
Data Redundancy & Update AnomaliesJens Patel
14.9K views16 slides
R Introduction by
R IntroductionR Introduction
R Introductionschamber
3.1K views20 slides
Introduction to R and R Studio by
Introduction to R and R StudioIntroduction to R and R Studio
Introduction to R and R StudioRupak Roy
504 views14 slides
C programming language tutorial by
C programming language tutorial C programming language tutorial
C programming language tutorial javaTpoint s
2.2K views47 slides
Error Detection & Recovery by
Error Detection & RecoveryError Detection & Recovery
Error Detection & RecoveryAkhil Kaushik
1.9K views23 slides
Daa by
DaaDaa
DaaDhananjay Singh
4.5K views80 slides

What's hot(20)

Data Redundancy & Update Anomalies by Jens Patel
Data Redundancy & Update AnomaliesData Redundancy & Update Anomalies
Data Redundancy & Update Anomalies
Jens Patel14.9K views
R Introduction by schamber
R IntroductionR Introduction
R Introduction
schamber3.1K views
Introduction to R and R Studio by Rupak Roy
Introduction to R and R StudioIntroduction to R and R Studio
Introduction to R and R Studio
Rupak Roy504 views
C programming language tutorial by javaTpoint s
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s2.2K views
Error Detection & Recovery by Akhil Kaushik
Error Detection & RecoveryError Detection & Recovery
Error Detection & Recovery
Akhil Kaushik1.9K views
2. R-basics, Vectors, Arrays, Matrices, Factors by krishna singh
2. R-basics, Vectors, Arrays, Matrices, Factors2. R-basics, Vectors, Arrays, Matrices, Factors
2. R-basics, Vectors, Arrays, Matrices, Factors
krishna singh1.9K views
Presentation on Function in C Programming by Shuvongkor Barman
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman14.7K views
Regular Expression in Compiler design by Riazul Islam
Regular Expression in Compiler designRegular Expression in Compiler design
Regular Expression in Compiler design
Riazul Islam4.1K views
File and directories in python by Lifna C.S
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S960 views
Learn C# Programming - Variables & Constants by Eng Teong Cheah
Learn C# Programming - Variables & ConstantsLearn C# Programming - Variables & Constants
Learn C# Programming - Variables & Constants
Eng Teong Cheah1.2K views
Introduction to data analysis using R by Victoria López
Introduction to data analysis using RIntroduction to data analysis using R
Introduction to data analysis using R
Victoria López 3.3K views
Introduction to Machine Learning with Find-S by Knoldus Inc.
Introduction to Machine Learning with Find-SIntroduction to Machine Learning with Find-S
Introduction to Machine Learning with Find-S
Knoldus Inc.8.2K views
Constants and variables in c programming by Chitrank Dixit
Constants and variables in c programmingConstants and variables in c programming
Constants and variables in c programming
Chitrank Dixit7.6K views

Viewers also liked

intro to knitr with RStudio by
intro to knitr with RStudiointro to knitr with RStudio
intro to knitr with RStudioBen Bolker
5.1K views19 slides
Markdown vs. WYSIWYG - Stop using the web like a word document by
Markdown vs. WYSIWYG - Stop using the web like a word document Markdown vs. WYSIWYG - Stop using the web like a word document
Markdown vs. WYSIWYG - Stop using the web like a word document Zensations GmbH
3.6K views12 slides
markedj: The best of markdown processor on JVM by
markedj: The best of markdown processor on JVMmarkedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMtakezoe
5.1K views13 slides
Let's learning Markdown by
Let's learning MarkdownLet's learning Markdown
Let's learning MarkdownWanqiang Ji
1.4K views12 slides
Markdown – An Introduction by
Markdown – An IntroductionMarkdown – An Introduction
Markdown – An IntroductionVenkatesh Narayanan
1.7K views12 slides
CommonMark: Markdown done right - Nomad PHP September 2016 by
CommonMark: Markdown done right - Nomad PHP September 2016CommonMark: Markdown done right - Nomad PHP September 2016
CommonMark: Markdown done right - Nomad PHP September 2016Colin O'Dell
1.1K views64 slides

Viewers also liked(20)

intro to knitr with RStudio by Ben Bolker
intro to knitr with RStudiointro to knitr with RStudio
intro to knitr with RStudio
Ben Bolker5.1K views
Markdown vs. WYSIWYG - Stop using the web like a word document by Zensations GmbH
Markdown vs. WYSIWYG - Stop using the web like a word document Markdown vs. WYSIWYG - Stop using the web like a word document
Markdown vs. WYSIWYG - Stop using the web like a word document
Zensations GmbH3.6K views
markedj: The best of markdown processor on JVM by takezoe
markedj: The best of markdown processor on JVMmarkedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVM
takezoe5.1K views
Let's learning Markdown by Wanqiang Ji
Let's learning MarkdownLet's learning Markdown
Let's learning Markdown
Wanqiang Ji1.4K views
CommonMark: Markdown done right - Nomad PHP September 2016 by Colin O'Dell
CommonMark: Markdown done right - Nomad PHP September 2016CommonMark: Markdown done right - Nomad PHP September 2016
CommonMark: Markdown done right - Nomad PHP September 2016
Colin O'Dell1.1K views
Markdown可以做什麼 by Yen-lung Tsai
Markdown可以做什麼Markdown可以做什麼
Markdown可以做什麼
Yen-lung Tsai2.5K views
Markdown - friend or foe? by Ellis Pratt
Markdown - friend or foe?Markdown - friend or foe?
Markdown - friend or foe?
Ellis Pratt1.5K views
Introduction to knitr - May Sheffield R Users group by Paul Richards
Introduction to knitr - May Sheffield R Users groupIntroduction to knitr - May Sheffield R Users group
Introduction to knitr - May Sheffield R Users group
Paul Richards976 views
Add plots and images to a word document using R software and ReporteRs package by kassambara
Add plots and images to a word document using R software and ReporteRs packageAdd plots and images to a word document using R software and ReporteRs package
Add plots and images to a word document using R software and ReporteRs package
kassambara69.2K views
Write book in markdown by Larry Cai
Write book in markdownWrite book in markdown
Write book in markdown
Larry Cai10.4K views
Introducing R Shiny and R notebook: R collaborative tools by Xavier Prudent
Introducing R Shiny and R notebook: R collaborative toolsIntroducing R Shiny and R notebook: R collaborative tools
Introducing R Shiny and R notebook: R collaborative tools
Xavier Prudent1.7K views
How to make keynote like presentation with markdown by Hiroaki NAKADA
How to make keynote like presentation with markdownHow to make keynote like presentation with markdown
How to make keynote like presentation with markdown
Hiroaki NAKADA7.6K views
Add a table of contents in a Word document using R software and ReporteRs pac... by kassambara
Add a table of contents in a Word document using R software and ReporteRs pac...Add a table of contents in a Word document using R software and ReporteRs pac...
Add a table of contents in a Word document using R software and ReporteRs pac...
kassambara69.1K views
Integrating R, knitr, and LaTeX via RStudio by Aaron Baggett
Integrating R, knitr, and LaTeX via RStudioIntegrating R, knitr, and LaTeX via RStudio
Integrating R, knitr, and LaTeX via RStudio
Aaron Baggett15.6K views

Similar to An introduction to knitr and R Markdown

R tools for HiC data visualization by
R tools for HiC data visualizationR tools for HiC data visualization
R tools for HiC data visualizationtuxette
668 views27 slides
Crosstalk by
CrosstalkCrosstalk
Crosstalkcdhowe
61 views40 slides
Modules and Scripts- Python Assignment Help by
Modules and Scripts- Python Assignment HelpModules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment HelpAnderson Silva
307 views48 slides
Methods by
MethodsMethods
MethodsAndy Juan Sarango Veliz
58 views62 slides
Matlab anilkumar by
Matlab  anilkumarMatlab  anilkumar
Matlab anilkumarTHEMASTERBLASTERSVID
94 views73 slides
TC39: How we work, what we are working on, and how you can get involved (dotJ... by
TC39: How we work, what we are working on, and how you can get involved (dotJ...TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...Igalia
205 views68 slides

Similar to An introduction to knitr and R Markdown(20)

R tools for HiC data visualization by tuxette
R tools for HiC data visualizationR tools for HiC data visualization
R tools for HiC data visualization
tuxette668 views
Crosstalk by cdhowe
CrosstalkCrosstalk
Crosstalk
cdhowe61 views
Modules and Scripts- Python Assignment Help by Anderson Silva
Modules and Scripts- Python Assignment HelpModules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment Help
Anderson Silva307 views
TC39: How we work, what we are working on, and how you can get involved (dotJ... by Igalia
TC39: How we work, what we are working on, and how you can get involved (dotJ...TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...
Igalia205 views
Csphtp1 03 by HUST
Csphtp1 03Csphtp1 03
Csphtp1 03
HUST469 views
Improving go-git performance by source{d}
Improving go-git performanceImproving go-git performance
Improving go-git performance
source{d}266 views
Project cs 3377 Computer Science homework help.pdf by sdfghj21
Project cs 3377 Computer Science homework help.pdfProject cs 3377 Computer Science homework help.pdf
Project cs 3377 Computer Science homework help.pdf
sdfghj218 views
Name _______________________________ Class time __________.docx by rosemarybdodson23141
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
maXbox Starter 43 Work with Code Metrics ISO Standard by Max Kleiner
maXbox Starter 43 Work with Code Metrics ISO StandardmaXbox Starter 43 Work with Code Metrics ISO Standard
maXbox Starter 43 Work with Code Metrics ISO Standard
Max Kleiner414 views
C and data structure by prabhatjon
C and data structureC and data structure
C and data structure
prabhatjon27.1K views
Csphtp1 06 by HUST
Csphtp1 06Csphtp1 06
Csphtp1 06
HUST701 views
GSP 125 Exceptional Education - snaptutorial.com by donaldzs162
GSP 125 Exceptional Education - snaptutorial.comGSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.com
donaldzs16214 views
GSP 125 Education Specialist / snaptutorial.com by stevesonz146
  GSP 125 Education Specialist / snaptutorial.com  GSP 125 Education Specialist / snaptutorial.com
GSP 125 Education Specialist / snaptutorial.com
stevesonz14635 views

More from sahirbhatnagar

Strong Heredity Models in High Dimensional Data by
Strong Heredity Models in High Dimensional DataStrong Heredity Models in High Dimensional Data
Strong Heredity Models in High Dimensional Datasahirbhatnagar
173 views53 slides
Methods for High Dimensional Interactions by
Methods for High Dimensional InteractionsMethods for High Dimensional Interactions
Methods for High Dimensional Interactionssahirbhatnagar
682 views94 slides
Atelier r-gerad by
Atelier r-geradAtelier r-gerad
Atelier r-geradsahirbhatnagar
1.9K views153 slides
Reproducible Research: An Introduction to knitr by
Reproducible Research: An Introduction to knitrReproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitrsahirbhatnagar
839 views43 slides
Analysis of DNA methylation and Gene expression to predict childhood obesity by
Analysis of DNA methylation and Gene expression to predict childhood obesityAnalysis of DNA methylation and Gene expression to predict childhood obesity
Analysis of DNA methylation and Gene expression to predict childhood obesitysahirbhatnagar
926 views33 slides
Estimation and Accuracy after Model Selection by
Estimation and Accuracy after Model SelectionEstimation and Accuracy after Model Selection
Estimation and Accuracy after Model Selectionsahirbhatnagar
1.1K views58 slides

More from sahirbhatnagar(12)

Strong Heredity Models in High Dimensional Data by sahirbhatnagar
Strong Heredity Models in High Dimensional DataStrong Heredity Models in High Dimensional Data
Strong Heredity Models in High Dimensional Data
sahirbhatnagar173 views
Methods for High Dimensional Interactions by sahirbhatnagar
Methods for High Dimensional InteractionsMethods for High Dimensional Interactions
Methods for High Dimensional Interactions
sahirbhatnagar682 views
Reproducible Research: An Introduction to knitr by sahirbhatnagar
Reproducible Research: An Introduction to knitrReproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitr
sahirbhatnagar839 views
Analysis of DNA methylation and Gene expression to predict childhood obesity by sahirbhatnagar
Analysis of DNA methylation and Gene expression to predict childhood obesityAnalysis of DNA methylation and Gene expression to predict childhood obesity
Analysis of DNA methylation and Gene expression to predict childhood obesity
sahirbhatnagar926 views
Estimation and Accuracy after Model Selection by sahirbhatnagar
Estimation and Accuracy after Model SelectionEstimation and Accuracy after Model Selection
Estimation and Accuracy after Model Selection
sahirbhatnagar1.1K views
Absolute risk estimation in a case cohort study of prostate cancer by sahirbhatnagar
Absolute risk estimation in a case cohort study of prostate cancerAbsolute risk estimation in a case cohort study of prostate cancer
Absolute risk estimation in a case cohort study of prostate cancer
sahirbhatnagar1.1K views
Computational methods for case-cohort studies by sahirbhatnagar
Computational methods for case-cohort studiesComputational methods for case-cohort studies
Computational methods for case-cohort studies
sahirbhatnagar1.6K views
Factors influencing participation in cancer screening by sahirbhatnagar
Factors influencing participation in cancer screeningFactors influencing participation in cancer screening
Factors influencing participation in cancer screening
sahirbhatnagar485 views
Methylation and Expression data integration by sahirbhatnagar
Methylation and Expression data integrationMethylation and Expression data integration
Methylation and Expression data integration
sahirbhatnagar643 views

Recently uploaded

Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe... by
Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe...Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe...
Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe...Anmol Vishnu Gupta
28 views12 slides
DEVELOPMENT OF FROG.pptx by
DEVELOPMENT OF FROG.pptxDEVELOPMENT OF FROG.pptx
DEVELOPMENT OF FROG.pptxsushant292556
11 views21 slides
Oral_Presentation_by_Fatma (2).pdf by
Oral_Presentation_by_Fatma (2).pdfOral_Presentation_by_Fatma (2).pdf
Oral_Presentation_by_Fatma (2).pdffatmaalmrzqi
8 views7 slides
BLOTTING TECHNIQUES SPECIAL by
BLOTTING TECHNIQUES SPECIALBLOTTING TECHNIQUES SPECIAL
BLOTTING TECHNIQUES SPECIALMuhammadImranMirza2
7 views56 slides
Applications of Large Language Models in Materials Discovery and Design by
Applications of Large Language Models in Materials Discovery and DesignApplications of Large Language Models in Materials Discovery and Design
Applications of Large Language Models in Materials Discovery and DesignAnubhav Jain
14 views17 slides
Indian council for child welfare by
Indian council for child welfareIndian council for child welfare
Indian council for child welfareRenuWaghmare2
7 views21 slides

Recently uploaded(20)

Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe... by Anmol Vishnu Gupta
Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe...Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe...
Study on Drug Drug Interaction Through Prescription Analysis of Type II Diabe...
Oral_Presentation_by_Fatma (2).pdf by fatmaalmrzqi
Oral_Presentation_by_Fatma (2).pdfOral_Presentation_by_Fatma (2).pdf
Oral_Presentation_by_Fatma (2).pdf
fatmaalmrzqi8 views
Applications of Large Language Models in Materials Discovery and Design by Anubhav Jain
Applications of Large Language Models in Materials Discovery and DesignApplications of Large Language Models in Materials Discovery and Design
Applications of Large Language Models in Materials Discovery and Design
Anubhav Jain14 views
Indian council for child welfare by RenuWaghmare2
Indian council for child welfareIndian council for child welfare
Indian council for child welfare
RenuWaghmare27 views
Small ruminant keepers’ knowledge, attitudes and practices towards peste des ... by ILRI
Small ruminant keepers’ knowledge, attitudes and practices towards peste des ...Small ruminant keepers’ knowledge, attitudes and practices towards peste des ...
Small ruminant keepers’ knowledge, attitudes and practices towards peste des ...
ILRI6 views
A giant thin stellar stream in the Coma Galaxy Cluster by Sérgio Sacani
A giant thin stellar stream in the Coma Galaxy ClusterA giant thin stellar stream in the Coma Galaxy Cluster
A giant thin stellar stream in the Coma Galaxy Cluster
Sérgio Sacani19 views
Small ruminant keepers’ knowledge, attitudes and practices towards peste des ... by ILRI
Small ruminant keepers’ knowledge, attitudes and practices towards peste des ...Small ruminant keepers’ knowledge, attitudes and practices towards peste des ...
Small ruminant keepers’ knowledge, attitudes and practices towards peste des ...
ILRI9 views
ELECTRON TRANSPORT CHAIN by DEEKSHA RANI
ELECTRON TRANSPORT CHAINELECTRON TRANSPORT CHAIN
ELECTRON TRANSPORT CHAIN
DEEKSHA RANI11 views
Discovery of therapeutic agents targeting PKLR for NAFLD using drug repositio... by Trustlife
Discovery of therapeutic agents targeting PKLR for NAFLD using drug repositio...Discovery of therapeutic agents targeting PKLR for NAFLD using drug repositio...
Discovery of therapeutic agents targeting PKLR for NAFLD using drug repositio...
Trustlife146 views
Effect of Integrated Nutrient Management on Growth and Yield of Solanaceous F... by SwagatBehera9
Effect of Integrated Nutrient Management on Growth and Yield of Solanaceous F...Effect of Integrated Nutrient Management on Growth and Yield of Solanaceous F...
Effect of Integrated Nutrient Management on Growth and Yield of Solanaceous F...
SwagatBehera95 views
selection of preformed arch wires during the alignment stage of preadjusted o... by MaherFouda1
selection of preformed arch wires during the alignment stage of preadjusted o...selection of preformed arch wires during the alignment stage of preadjusted o...
selection of preformed arch wires during the alignment stage of preadjusted o...
MaherFouda17 views

An introduction to knitr and R Markdown

  • 1. An Introduction to knitr and RMarkdown https://github.com/sahirbhatnagar/knitr-tutorial Sahir Bhatnagar August 12, 2015 McGill Univeristy
  • 2. Acknowledgements • Toby, Matthieu, Vaughn, Ary • Maxime Turgeon (Windows) • Kevin McGregor (Mac) • Greg Voisin • Don Knuth (TEX) • Friedrich Leisch (Sweave) • Yihui Xie (knitr) • John Gruber (Markdown) • John MacFarlane (Pandoc) • You 2/36
  • 3. Disclaimer #1 I don’t work for, nor am I an author of any of these packages. I’m just a messenger. 3/36
  • 4. Disclaimer #2 • Material for this tutorial comes from many sources. For a complete list see: https://github.com/sahirbhatnagar/knitr-tutorial • Alot of the content in these slides are based on these two books 4/36
  • 5. Objectives for today • Create a reproducible document (pdf, html) 5/36
  • 6. Objectives for today • Create a reproducible document (pdf, html) 5/36
  • 9. What is needed for Reproducible research? code data text 8/36
  • 10. Why?
  • 11. Why should we care about RR? For Science Standard to judge scientific claims Avoid duplication Cumulative knowledge development
  • 12. Why should we care about RR? For Science Standard to judge scientific claims Avoid duplication Cumulative knowledge development For You Better work habits Better teamwork Changes are easier Higher re- search impact 10/36
  • 14. A Motivating Example Demonstrate: 001-motivating-example 12/36
  • 15. How?
  • 16. Tools for Reproducible Research Free and Open Source Software • RStudio: Creating, managing, compiling documents • LATEX: Markup language for typesetting a pdf • Markdown: Markup language for typesetting an html • R: Statistical analysis language • knitr: Integrate LATEXand R code. Based on Prof. Friedrich Leisch’s Sweave 14/36
  • 17. knitr
  • 18. What knitr does LATEX example: Report.Rnw (contains both code and LaTeX) Report.tex knitr::knit(’Report.Rnw’)
  • 19. What knitr does LATEX example: Report.Rnw (contains both code and LaTeX) Report.tex knitr::knit(’Report.Rnw’) Report.pdf latex2pdf(’Report.tex’) 16/36
  • 20. Compiling a .Rnw document The two steps on previous slide can be executed in one com- mand: knitr::knit2pdf() or in RStudio: 17/36
  • 21. Incorporating R code • Insert R code in a Code Chunk starting with << >>= and ending with @ In RStudio: 18/36
  • 22. Example 1: Show code and results <<example-code-chunk-name, echo=TRUE>>= x <- rnorm(50) mean(x) @ produces x <- rnorm(50) mean(x) ## [1] 0.031 19/36
  • 23. Example 2: Tidy code <<example-code-chunk-name2, echo=TRUE, tidy=TRUE>>= for(i in 1:5){ print(i+3)} @ produces for (i in 1:5) { print(i + 3) } ## [1] 4 ## [1] 5 ## [1] 6 ## [1] 7 ## [1] 8 20/36
  • 24. Example 2.2: don’t show code <<example-code-chunk-name3, echo=FALSE>>= for(i in 1:5){ print(i+3)} @ produces ## [1] 4 ## [1] 5 ## [1] 6 ## [1] 7 ## [1] 8 21/36
  • 25. Example 2.3: don’t evaluate and don’t show the code <<example-code-chunk-name4, echo=FALSE, eval=FALSE>>= for(i in 1:5){ print(i+3)} @ produces 22/36
  • 26. R output within the text • Include R output within the text • We can do that with“S-expressions”using the command Sexpr{. . .} Example: The iris dataset has Sexpr{nrow(iris)} rows and Sexpr{ncol(iris)} columns produces The iris dataset has 150 rows and 5 columns 23/36
  • 27. Include a Figure <<fig.ex, fig.cap='Linear Regression',fig.height=3,fig.width=3>>= plot(mtcars[ , c('disp','mpg')]) fit <- lm(mpg ~ disp , data = mtcars) abline(fit,lwd=2) @ qqq q qq q qq qq qq q qq q q q q q qq q q q q q q q q q 100 200 300 400 1025 disp mpg Figure 1: Linear regression 24/36
  • 28. Include a Table <<table.ex, results='asis'>>= library(xtable) tab <- xtable(iris[1:5,1:5],caption='Sample of Iris data') print(tab, include.rownames=FALSE) @ library(xtable) tab <- xtable(iris[1:5,1:5], caption = 'Sample of Iris data') print(tab, include.rownames = F) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 5.10 3.50 1.40 0.20 setosa 4.90 3.00 1.40 0.20 setosa 4.70 3.20 1.30 0.20 setosa 4.60 3.10 1.50 0.20 setosa 5.00 3.60 1.40 0.20 setosa Table 1: Sample of Iris data 25/36
  • 30. Markdown: HTML without knowing HTML 27/36
  • 31. R + Markdown = RMarkdown 28/36
  • 32. What rmarkdown does RMarkdown example: Report.Rmd (contains both code and markdown) Report.md knitr::knit(’Report.Rmd’)
  • 33. What rmarkdown does RMarkdown example: Report.Rmd (contains both code and markdown) Report.md knitr::knit(’Report.Rmd’) Report.html, Report.pdf, Report.doc pandoc 29/36
  • 34. Compiling a .Rmd document The two steps on previous slide can be executed in one com- mand: rmarkdown::render() or in RStudio: 30/36
  • 36. How to choose between LATEX and Markdown ? math/stat symbols tecccccc beamer presentations teccccc customized documents tecccc publish to journals, arXiv quick and easy reportstkkk use javascript libraries tekkt interactive plots texkkkkjjt publish to websites LATEX Markdown 32/36
  • 37. 33/36
  • 38. Always Remember ... Reproducibility ∝ 1 copy paste 34/36
  • 39. Is the juice worth the squeeze? 35/36
  • 40. Session Info • R version 3.2.1 (2015-06-18), x86_64-pc-linux-gnu • Base packages: base, datasets, graphics, grDevices, methods, stats, utils • Other packages: data.table 1.9.4, dplyr 0.4.1, ggplot2 1.0.1, knitr 1.10.5, xtable 1.7-4 • Loaded via a namespace (and not attached): assertthat 0.1, chron 2.3-45, colorspace 1.2-6, DBI 0.3.1, digest 0.6.8, evaluate 0.7, formatR 1.2, grid 3.2.1, gtable 0.1.2, highr 0.5, magrittr 1.5, MASS 7.3-43, munsell 0.4.2, parallel 3.2.1, plyr 1.8.3, proto 0.3-10, Rcpp 0.12.0, reshape2 1.4.1, scales 0.2.5, stringi 0.5-5, stringr 1.0.0, tools 3.2.1 Slides made with Beamer mtheme 36/36