SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Machine learning and linear regression programming
Machine learning and linear regression programmingMachine learning and linear regression programming
Machine learning and linear regression programmingSoumya Mukherjee
 
Machine Learning Algorithms
Machine Learning AlgorithmsMachine Learning Algorithms
Machine Learning AlgorithmsHichem Felouat
 
Introduction to Linear Discriminant Analysis
Introduction to Linear Discriminant AnalysisIntroduction to Linear Discriminant Analysis
Introduction to Linear Discriminant AnalysisJaclyn Kokx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptBryan Basham
 
R data-import, data-export
R data-import, data-exportR data-import, data-export
R data-import, data-exportFAO
 
Birch Algorithm With Solved Example
Birch Algorithm With Solved ExampleBirch Algorithm With Solved Example
Birch Algorithm With Solved Examplekailash shaw
 
Chart and graphs in R programming language
Chart and graphs in R programming language Chart and graphs in R programming language
Chart and graphs in R programming language CHANDAN KUMAR
 
Machine Learning-Linear regression
Machine Learning-Linear regressionMachine Learning-Linear regression
Machine Learning-Linear regressionkishanthkumaar
 
Introduction to R Programming
Introduction to R ProgrammingIntroduction to R Programming
Introduction to R Programmingizahn
 
Clustering, k-means clustering
Clustering, k-means clusteringClustering, k-means clustering
Clustering, k-means clusteringMegha Sharma
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements IReem Alattas
 

Was ist angesagt? (20)

Machine learning and linear regression programming
Machine learning and linear regression programmingMachine learning and linear regression programming
Machine learning and linear regression programming
 
CSS selectors
CSS selectorsCSS selectors
CSS selectors
 
Machine Learning Algorithms
Machine Learning AlgorithmsMachine Learning Algorithms
Machine Learning Algorithms
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Unit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptxUnit 1 - R Programming (Part 2).pptx
Unit 1 - R Programming (Part 2).pptx
 
CSS Grid
CSS GridCSS Grid
CSS Grid
 
Introduction to Linear Discriminant Analysis
Introduction to Linear Discriminant AnalysisIntroduction to Linear Discriminant Analysis
Introduction to Linear Discriminant Analysis
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
R data-import, data-export
R data-import, data-exportR data-import, data-export
R data-import, data-export
 
Birch Algorithm With Solved Example
Birch Algorithm With Solved ExampleBirch Algorithm With Solved Example
Birch Algorithm With Solved Example
 
Chart and graphs in R programming language
Chart and graphs in R programming language Chart and graphs in R programming language
Chart and graphs in R programming language
 
Machine Learning-Linear regression
Machine Learning-Linear regressionMachine Learning-Linear regression
Machine Learning-Linear regression
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
An Overview of Simple Linear Regression
An Overview of Simple Linear RegressionAn Overview of Simple Linear Regression
An Overview of Simple Linear Regression
 
Introduction to R Programming
Introduction to R ProgrammingIntroduction to R Programming
Introduction to R Programming
 
Clustering, k-means clustering
Clustering, k-means clusteringClustering, k-means clustering
Clustering, k-means clustering
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements I
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
 
Logistical Regression.pptx
Logistical Regression.pptxLogistical Regression.pptx
Logistical Regression.pptx
 

Andere mochten auch

intro to knitr with RStudio
intro to knitr with RStudiointro to knitr with RStudio
intro to knitr with RStudioBen Bolker
 
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
Markdown vs. WYSIWYG - Stop using the web like a word document Zensations GmbH
 
markedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMmarkedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMtakezoe
 
Let's learning Markdown
Let's learning MarkdownLet's learning Markdown
Let's learning MarkdownWanqiang Ji
 
CommonMark: Markdown done right - Nomad PHP September 2016
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
 
Markdown可以做什麼
Markdown可以做什麼Markdown可以做什麼
Markdown可以做什麼Yen-lung Tsai
 
Markdown - friend or foe?
Markdown - friend or foe?Markdown - friend or foe?
Markdown - friend or foe?Ellis Pratt
 
Introduction to knitr - May Sheffield R Users group
Introduction to knitr - May Sheffield R Users groupIntroduction to knitr - May Sheffield R Users group
Introduction to knitr - May Sheffield R Users groupPaul Richards
 
Add 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 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 packagekassambara
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdownLarry Cai
 
Introducing R Shiny and R notebook: R collaborative tools
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 toolsXavier Prudent
 
How to make keynote like presentation with markdown
How to make keynote like presentation with markdownHow to make keynote like presentation with markdown
How to make keynote like presentation with markdownHiroaki NAKADA
 
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...
Add a table of contents in a Word document using R software and ReporteRs pac...kassambara
 
Integrating R, knitr, and LaTeX via RStudio
Integrating R, knitr, and LaTeX via RStudioIntegrating R, knitr, and LaTeX via RStudio
Integrating R, knitr, and LaTeX via RStudioAaron Baggett
 
Die Magie von Markdown
Die Magie von MarkdownDie Magie von Markdown
Die Magie von MarkdownHendrik Spree
 

Andere mochten auch (20)

intro to knitr with RStudio
intro to knitr with RStudiointro to knitr with RStudio
intro to knitr with RStudio
 
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
Markdown vs. WYSIWYG - Stop using the web like a word document
 
markedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVMmarkedj: The best of markdown processor on JVM
markedj: The best of markdown processor on JVM
 
Let's learning Markdown
Let's learning MarkdownLet's learning Markdown
Let's learning Markdown
 
Markdown – An Introduction
Markdown – An IntroductionMarkdown – An Introduction
Markdown – An Introduction
 
CommonMark: Markdown done right - Nomad PHP September 2016
CommonMark: Markdown done right - Nomad PHP September 2016CommonMark: Markdown done right - Nomad PHP September 2016
CommonMark: Markdown done right - Nomad PHP September 2016
 
Markdown Slides [EN]
Markdown Slides [EN]Markdown Slides [EN]
Markdown Slides [EN]
 
Take it easy with markdown
Take it easy with markdownTake it easy with markdown
Take it easy with markdown
 
Markdown可以做什麼
Markdown可以做什麼Markdown可以做什麼
Markdown可以做什麼
 
Markdown - friend or foe?
Markdown - friend or foe?Markdown - friend or foe?
Markdown - friend or foe?
 
Introduction to knitr - May Sheffield R Users group
Introduction to knitr - May Sheffield R Users groupIntroduction to knitr - May Sheffield R Users group
Introduction to knitr - May Sheffield R Users group
 
Add 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 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
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdown
 
Introducing R Shiny and R notebook: R collaborative tools
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
 
How to make keynote like presentation with markdown
How to make keynote like presentation with markdownHow to make keynote like presentation with markdown
How to make keynote like presentation with markdown
 
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...
Add a table of contents in a Word document using R software and ReporteRs pac...
 
R in latex
R in latexR in latex
R in latex
 
Integrating R, knitr, and LaTeX via RStudio
Integrating R, knitr, and LaTeX via RStudioIntegrating R, knitr, and LaTeX via RStudio
Integrating R, knitr, and LaTeX via RStudio
 
Beamer modelo2013
Beamer modelo2013Beamer modelo2013
Beamer modelo2013
 
Die Magie von Markdown
Die Magie von MarkdownDie Magie von Markdown
Die Magie von Markdown
 

Ähnlich wie An introduction to knitr and R Markdown

R tools for HiC data visualization
R tools for HiC data visualizationR tools for HiC data visualization
R tools for HiC data visualizationtuxette
 
Crosstalk
CrosstalkCrosstalk
Crosstalkcdhowe
 
Modules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment HelpModules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment HelpAnderson Silva
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptxMATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptxprashantkumarchinama
 
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...
TC39: How we work, what we are working on, and how you can get involved (dotJ...Igalia
 
Csphtp1 03
Csphtp1 03Csphtp1 03
Csphtp1 03HUST
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performancesource{d}
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docxrosemarybdodson23141
 
maXbox Starter 43 Work with Code Metrics ISO Standard
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 StandardMax Kleiner
 
C and data structure
C and data structureC and data structure
C and data structureprabhatjon
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentationBryan Reinero
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06HUST
 
Troubleshooting .net core on linux
Troubleshooting .net core on linuxTroubleshooting .net core on linux
Troubleshooting .net core on linuxPavel Klimiankou
 
GSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.comGSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.comdonaldzs162
 
GSP 125 Education Specialist / snaptutorial.com
  GSP 125 Education Specialist / snaptutorial.com  GSP 125 Education Specialist / snaptutorial.com
GSP 125 Education Specialist / snaptutorial.comstevesonz146
 

Ähnlich wie An introduction to knitr and R Markdown (20)

R tools for HiC data visualization
R tools for HiC data visualizationR tools for HiC data visualization
R tools for HiC data visualization
 
Crosstalk
CrosstalkCrosstalk
Crosstalk
 
Modules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment HelpModules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment Help
 
Methods
MethodsMethods
Methods
 
Matlab anilkumar
Matlab  anilkumarMatlab  anilkumar
Matlab anilkumar
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptxMATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
 
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...
TC39: How we work, what we are working on, and how you can get involved (dotJ...
 
Learning postgresql
Learning postgresqlLearning postgresql
Learning postgresql
 
Csphtp1 03
Csphtp1 03Csphtp1 03
Csphtp1 03
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performance
 
Solr sparse faceting
Solr sparse facetingSolr sparse faceting
Solr sparse faceting
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
 
maXbox Starter 43 Work with Code Metrics ISO Standard
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
 
C and data structure
C and data structureC and data structure
C and data structure
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
 
A01 assignment-1
A01 assignment-1A01 assignment-1
A01 assignment-1
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
 
Troubleshooting .net core on linux
Troubleshooting .net core on linuxTroubleshooting .net core on linux
Troubleshooting .net core on linux
 
GSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.comGSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.com
 
GSP 125 Education Specialist / snaptutorial.com
  GSP 125 Education Specialist / snaptutorial.com  GSP 125 Education Specialist / snaptutorial.com
GSP 125 Education Specialist / snaptutorial.com
 

Mehr von sahirbhatnagar

Strong Heredity Models in High Dimensional Data
Strong Heredity Models in High Dimensional DataStrong Heredity Models in High Dimensional Data
Strong Heredity Models in High Dimensional Datasahirbhatnagar
 
Methods for High Dimensional Interactions
Methods for High Dimensional InteractionsMethods for High Dimensional Interactions
Methods for High Dimensional Interactionssahirbhatnagar
 
Reproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitrReproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitrsahirbhatnagar
 
Analysis of DNA methylation and Gene expression to predict childhood obesity
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
 
Estimation and Accuracy after Model Selection
Estimation and Accuracy after Model SelectionEstimation and Accuracy after Model Selection
Estimation and Accuracy after Model Selectionsahirbhatnagar
 
Absolute risk estimation in a case cohort study of prostate cancer
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 cancersahirbhatnagar
 
Computational methods for case-cohort studies
Computational methods for case-cohort studiesComputational methods for case-cohort studies
Computational methods for case-cohort studiessahirbhatnagar
 
Factors influencing participation in cancer screening
Factors influencing participation in cancer screeningFactors influencing participation in cancer screening
Factors influencing participation in cancer screeningsahirbhatnagar
 
Methylation and Expression data integration
Methylation and Expression data integrationMethylation and Expression data integration
Methylation and Expression data integrationsahirbhatnagar
 

Mehr von sahirbhatnagar (12)

Strong Heredity Models in High Dimensional Data
Strong Heredity Models in High Dimensional DataStrong Heredity Models in High Dimensional Data
Strong Heredity Models in High Dimensional Data
 
Methods for High Dimensional Interactions
Methods for High Dimensional InteractionsMethods for High Dimensional Interactions
Methods for High Dimensional Interactions
 
Atelier r-gerad
Atelier r-geradAtelier r-gerad
Atelier r-gerad
 
Reproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitrReproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitr
 
Analysis of DNA methylation and Gene expression to predict childhood obesity
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
 
Estimation and Accuracy after Model Selection
Estimation and Accuracy after Model SelectionEstimation and Accuracy after Model Selection
Estimation and Accuracy after Model Selection
 
Absolute risk estimation in a case cohort study of prostate cancer
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
 
Computational methods for case-cohort studies
Computational methods for case-cohort studiesComputational methods for case-cohort studies
Computational methods for case-cohort studies
 
Factors influencing participation in cancer screening
Factors influencing participation in cancer screeningFactors influencing participation in cancer screening
Factors influencing participation in cancer screening
 
Introduction to LaTeX
Introduction to LaTeXIntroduction to LaTeX
Introduction to LaTeX
 
Methylation and Expression data integration
Methylation and Expression data integrationMethylation and Expression data integration
Methylation and Expression data integration
 
Reproducible Research
Reproducible ResearchReproducible Research
Reproducible Research
 

Kürzlich hochgeladen

Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxgindu3009
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Sérgio Sacani
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfSwapnil Therkar
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCEPRINCE C P
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTSérgio Sacani
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PPRINCE C P
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhousejana861314
 
Types of different blotting techniques.pptx
Types of different blotting techniques.pptxTypes of different blotting techniques.pptx
Types of different blotting techniques.pptxkhadijarafiq2012
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...Sérgio Sacani
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxpradhanghanshyam7136
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxAArockiyaNisha
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...RohitNehra6
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Natural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsNatural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsAArockiyaNisha
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisDiwakar Mishra
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSarthak Sekhar Mondal
 

Kürzlich hochgeladen (20)

Presentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptxPresentation Vikram Lander by Vedansh Gupta.pptx
Presentation Vikram Lander by Vedansh Gupta.pptx
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
 
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
 
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
9953056974 Young Call Girls In Mahavir enclave Indian Quality Escort service
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOST
 
Artificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C PArtificial Intelligence In Microbiology by Dr. Prince C P
Artificial Intelligence In Microbiology by Dr. Prince C P
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
The Philosophy of Science
The Philosophy of ScienceThe Philosophy of Science
The Philosophy of Science
 
Orientation, design and principles of polyhouse
Orientation, design and principles of polyhouseOrientation, design and principles of polyhouse
Orientation, design and principles of polyhouse
 
Types of different blotting techniques.pptx
Types of different blotting techniques.pptxTypes of different blotting techniques.pptx
Types of different blotting techniques.pptx
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptx
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...
 
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Munirka Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Natural Polymer Based Nanomaterials
Natural Polymer Based NanomaterialsNatural Polymer Based Nanomaterials
Natural Polymer Based Nanomaterials
 
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral AnalysisRaman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
Raman spectroscopy.pptx M Pharm, M Sc, Advanced Spectral Analysis
 
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatidSpermiogenesis or Spermateleosis or metamorphosis of spermatid
Spermiogenesis or Spermateleosis or metamorphosis of spermatid
 
Engler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomyEngler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomy
 

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