SlideShare a Scribd company logo
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

More Related Content

What's hot

Unit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptxUnit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptx
Malla Reddy University
 
Data Types and Structures in R
Data Types and Structures in RData Types and Structures in R
Data Types and Structures in R
Rupak Roy
 
R Programming
R ProgrammingR Programming
R Programming
Abhishek Pratap Singh
 
My8clst
My8clstMy8clst
My8clst
ketan533
 
Recurrent Neural Network : Multi-Class & Multi Label Text Classification
Recurrent Neural Network : Multi-Class & Multi Label Text ClassificationRecurrent Neural Network : Multi-Class & Multi Label Text Classification
Recurrent Neural Network : Multi-Class & Multi Label Text Classification
Amit Agarwal
 
【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み
【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み
【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み
The 20th annual meeting of Japanese Society of Digital Pathology
 
A Heart Disease Prediction Model using Logistic Regression
A Heart Disease Prediction Model using Logistic RegressionA Heart Disease Prediction Model using Logistic Regression
A Heart Disease Prediction Model using Logistic Regression
ijtsrd
 
Graphics in R
Graphics in RGraphics in R
Graphics in R
Kamal Gupta Roy
 
Metadata and ADaM
Metadata and ADaMMetadata and ADaM
Metadata and ADaM
Kevin Lee
 
Data analytics with R
Data analytics with RData analytics with R
Data analytics with R
Dr. C.V. Suresh Babu
 
[ppt]
[ppt][ppt]
[ppt]
butest
 
20161225午後検索式作成w sv1218答え抜き
20161225午後検索式作成w sv1218答え抜き20161225午後検索式作成w sv1218答え抜き
20161225午後検索式作成w sv1218答え抜き
SR WS
 
Knn 160904075605-converted
Knn 160904075605-convertedKnn 160904075605-converted
Knn 160904075605-converted
rameswara reddy venkat
 
Introduction to R - from Rstudio to ggplot
Introduction to R - from Rstudio to ggplotIntroduction to R - from Rstudio to ggplot
Introduction to R - from Rstudio to ggplot
Olga Scrivner
 
Support vector machine
Support vector machineSupport vector machine
Support vector machine
Musa Hawamdah
 
A Survey on Machine Learning Algorithms
A Survey on Machine Learning AlgorithmsA Survey on Machine Learning Algorithms
A Survey on Machine Learning Algorithms
AM Publications
 
GAN Evaluation
GAN EvaluationGAN Evaluation
GAN Evaluation
Dongheon Lee
 
svm classification
svm classificationsvm classification
svm classification
Akhilesh Joshi
 
Bayesian Belief Networks for dummies
Bayesian Belief Networks for dummiesBayesian Belief Networks for dummies
Bayesian Belief Networks for dummies
Gilad Barkan
 
A quick demo of Top2Vec With application on 2020 10-K business descriptions
A quick demo of Top2Vec With application on 2020 10-K business descriptionsA quick demo of Top2Vec With application on 2020 10-K business descriptions
A quick demo of Top2Vec With application on 2020 10-K business descriptions
Gautier Marti
 

What's hot (20)

Unit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptxUnit 2 - Data Manipulation with R.pptx
Unit 2 - Data Manipulation with R.pptx
 
Data Types and Structures in R
Data Types and Structures in RData Types and Structures in R
Data Types and Structures in R
 
R Programming
R ProgrammingR Programming
R Programming
 
My8clst
My8clstMy8clst
My8clst
 
Recurrent Neural Network : Multi-Class & Multi Label Text Classification
Recurrent Neural Network : Multi-Class & Multi Label Text ClassificationRecurrent Neural Network : Multi-Class & Multi Label Text Classification
Recurrent Neural Network : Multi-Class & Multi Label Text Classification
 
【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み
【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み
【浜松ホトニクス】浜松ホトニクスの病理ネットワーク化への取り組み
 
A Heart Disease Prediction Model using Logistic Regression
A Heart Disease Prediction Model using Logistic RegressionA Heart Disease Prediction Model using Logistic Regression
A Heart Disease Prediction Model using Logistic Regression
 
Graphics in R
Graphics in RGraphics in R
Graphics in R
 
Metadata and ADaM
Metadata and ADaMMetadata and ADaM
Metadata and ADaM
 
Data analytics with R
Data analytics with RData analytics with R
Data analytics with R
 
[ppt]
[ppt][ppt]
[ppt]
 
20161225午後検索式作成w sv1218答え抜き
20161225午後検索式作成w sv1218答え抜き20161225午後検索式作成w sv1218答え抜き
20161225午後検索式作成w sv1218答え抜き
 
Knn 160904075605-converted
Knn 160904075605-convertedKnn 160904075605-converted
Knn 160904075605-converted
 
Introduction to R - from Rstudio to ggplot
Introduction to R - from Rstudio to ggplotIntroduction to R - from Rstudio to ggplot
Introduction to R - from Rstudio to ggplot
 
Support vector machine
Support vector machineSupport vector machine
Support vector machine
 
A Survey on Machine Learning Algorithms
A Survey on Machine Learning AlgorithmsA Survey on Machine Learning Algorithms
A Survey on Machine Learning Algorithms
 
GAN Evaluation
GAN EvaluationGAN Evaluation
GAN Evaluation
 
svm classification
svm classificationsvm classification
svm classification
 
Bayesian Belief Networks for dummies
Bayesian Belief Networks for dummiesBayesian Belief Networks for dummies
Bayesian Belief Networks for dummies
 
A quick demo of Top2Vec With application on 2020 10-K business descriptions
A quick demo of Top2Vec With application on 2020 10-K business descriptionsA quick demo of Top2Vec With application on 2020 10-K business descriptions
A quick demo of Top2Vec With application on 2020 10-K business descriptions
 

Viewers also liked

intro to knitr with RStudio
intro to knitr with RStudiointro to knitr with RStudio
intro to knitr with RStudio
Ben 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 JVM
takezoe
 
Let's learning Markdown
Let's learning MarkdownLet's learning Markdown
Let's learning Markdown
Wanqiang Ji
 
Markdown – An Introduction
Markdown – An IntroductionMarkdown – An Introduction
Markdown – An Introduction
Venkatesh Narayanan
 
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
Colin O'Dell
 
Markdown Slides [EN]
Markdown Slides [EN]Markdown Slides [EN]
Markdown Slides [EN]
Adolfo Sanz De Diego
 
Take it easy with markdown
Take it easy with markdownTake it easy with markdown
Take it easy with markdown
Lukasz Kosma Bonenberg
 
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 group
Paul 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 package
kassambara
 
Write book in markdown
Write book in markdownWrite book in markdown
Write book in markdown
Larry 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 tools
Xavier 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 markdown
Hiroaki 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
 
R in latex
R in latexR in latex
R in latex
Julyan Arbel
 
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
Aaron Baggett
 
Beamer modelo2013
Beamer modelo2013Beamer modelo2013
Beamer modelo2013
Regis da Silva
 
Die Magie von Markdown
Die Magie von MarkdownDie Magie von Markdown
Die Magie von Markdown
Hendrik Spree
 

Viewers also liked (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
 

Similar to 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 visualization
tuxette
 
Crosstalk
CrosstalkCrosstalk
Crosstalk
cdhowe
 
Modules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment HelpModules and Scripts- Python Assignment Help
Modules and Scripts- Python Assignment Help
Anderson Silva
 
Methods
MethodsMethods
Matlab anilkumar
Matlab  anilkumarMatlab  anilkumar
Matlab anilkumar
THEMASTERBLASTERSVID
 
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptxMATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
MATLAB Workshop yugjjnhhasfhlhhlllhl.pptx
prashantkumarchinama
 
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
 
Learning postgresql
Learning postgresqlLearning postgresql
Learning postgresql
DAVID RAUDALES
 
Csphtp1 03
Csphtp1 03Csphtp1 03
Csphtp1 03
HUST
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performance
source{d}
 
Solr sparse faceting
Solr sparse facetingSolr sparse faceting
Solr sparse faceting
Toke Eskildsen
 
Name _______________________________ Class time __________.docx
Name _______________________________    Class time __________.docxName _______________________________    Class time __________.docx
Name _______________________________ Class time __________.docx
rosemarybdodson23141
 
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
Max Kleiner
 
C and data structure
C and data structureC and data structure
C and data structure
prabhatjon
 
Code instrumentation
Code instrumentationCode instrumentation
Code instrumentation
Bryan Reinero
 
A01 assignment-1
A01 assignment-1A01 assignment-1
A01 assignment-1
Sandeep Ratnam
 
Csphtp1 06
Csphtp1 06Csphtp1 06
Csphtp1 06
HUST
 
Troubleshooting .net core on linux
Troubleshooting .net core on linuxTroubleshooting .net core on linux
Troubleshooting .net core on linux
Pavel Klimiankou
 
GSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.comGSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.com
donaldzs162
 
GSP 125 Education Specialist / snaptutorial.com
  GSP 125 Education Specialist / snaptutorial.com  GSP 125 Education Specialist / snaptutorial.com
GSP 125 Education Specialist / snaptutorial.com
stevesonz146
 

Similar to 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
 

More from 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 Data
sahirbhatnagar
 
Methods for High Dimensional Interactions
Methods for High Dimensional InteractionsMethods for High Dimensional Interactions
Methods for High Dimensional Interactions
sahirbhatnagar
 
Atelier r-gerad
Atelier r-geradAtelier r-gerad
Atelier r-gerad
sahirbhatnagar
 
Reproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitrReproducible Research: An Introduction to knitr
Reproducible Research: An Introduction to knitr
sahirbhatnagar
 
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
sahirbhatnagar
 
Estimation and Accuracy after Model Selection
Estimation and Accuracy after Model SelectionEstimation and Accuracy after Model Selection
Estimation and Accuracy after Model Selection
sahirbhatnagar
 
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
sahirbhatnagar
 
Computational methods for case-cohort studies
Computational methods for case-cohort studiesComputational methods for case-cohort studies
Computational methods for case-cohort studies
sahirbhatnagar
 
Factors influencing participation in cancer screening
Factors influencing participation in cancer screeningFactors influencing participation in cancer screening
Factors influencing participation in cancer screening
sahirbhatnagar
 
Introduction to LaTeX
Introduction to LaTeXIntroduction to LaTeX
Introduction to LaTeX
sahirbhatnagar
 
Methylation and Expression data integration
Methylation and Expression data integrationMethylation and Expression data integration
Methylation and Expression data integration
sahirbhatnagar
 
Reproducible Research
Reproducible ResearchReproducible Research
Reproducible Research
sahirbhatnagar
 

More from 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
 

Recently uploaded

aziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobelaziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobel
İsa Badur
 
ESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptxESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptx
PRIYANKA PATEL
 
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdfwaterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
LengamoLAppostilic
 
Shallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptxShallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptx
Gokturk Mehmet Dilci
 
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills MN
 
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptxThe use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
MAGOTI ERNEST
 
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
vluwdy49
 
bordetella pertussis.................................ppt
bordetella pertussis.................................pptbordetella pertussis.................................ppt
bordetella pertussis.................................ppt
kejapriya1
 
SAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdfSAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdf
KrushnaDarade1
 
The binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defectsThe binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defects
Sérgio Sacani
 
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdfTopic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
TinyAnderson
 
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
David Osipyan
 
Compexometric titration/Chelatorphy titration/chelating titration
Compexometric titration/Chelatorphy titration/chelating titrationCompexometric titration/Chelatorphy titration/chelating titration
Compexometric titration/Chelatorphy titration/chelating titration
Vandana Devesh Sharma
 
Thornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdfThornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdf
European Sustainable Phosphorus Platform
 
Medical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptxMedical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptx
terusbelajar5
 
8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf
by6843629
 
Cytokines and their role in immune regulation.pptx
Cytokines and their role in immune regulation.pptxCytokines and their role in immune regulation.pptx
Cytokines and their role in immune regulation.pptx
Hitesh Sikarwar
 
NuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyerNuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyer
pablovgd
 
Describing and Interpreting an Immersive Learning Case with the Immersion Cub...
Describing and Interpreting an Immersive Learning Case with the Immersion Cub...Describing and Interpreting an Immersive Learning Case with the Immersion Cub...
Describing and Interpreting an Immersive Learning Case with the Immersion Cub...
Leonel Morgado
 
Phenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvementPhenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvement
IshaGoswami9
 

Recently uploaded (20)

aziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobelaziz sancar nobel prize winner: from mardin to nobel
aziz sancar nobel prize winner: from mardin to nobel
 
ESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptxESR spectroscopy in liquid food and beverages.pptx
ESR spectroscopy in liquid food and beverages.pptx
 
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdfwaterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
waterlessdyeingtechnolgyusing carbon dioxide chemicalspdf
 
Shallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptxShallowest Oil Discovery of Turkiye.pptx
Shallowest Oil Discovery of Turkiye.pptx
 
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
 
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptxThe use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
The use of Nauplii and metanauplii artemia in aquaculture (brine shrimp).pptx
 
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
在线办理(salfor毕业证书)索尔福德大学毕业证毕业完成信一模一样
 
bordetella pertussis.................................ppt
bordetella pertussis.................................pptbordetella pertussis.................................ppt
bordetella pertussis.................................ppt
 
SAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdfSAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdf
 
The binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defectsThe binding of cosmological structures by massless topological defects
The binding of cosmological structures by massless topological defects
 
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdfTopic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
Topic: SICKLE CELL DISEASE IN CHILDREN-3.pdf
 
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
 
Compexometric titration/Chelatorphy titration/chelating titration
Compexometric titration/Chelatorphy titration/chelating titrationCompexometric titration/Chelatorphy titration/chelating titration
Compexometric titration/Chelatorphy titration/chelating titration
 
Thornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdfThornton ESPP slides UK WW Network 4_6_24.pdf
Thornton ESPP slides UK WW Network 4_6_24.pdf
 
Medical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptxMedical Orthopedic PowerPoint Templates.pptx
Medical Orthopedic PowerPoint Templates.pptx
 
8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf8.Isolation of pure cultures and preservation of cultures.pdf
8.Isolation of pure cultures and preservation of cultures.pdf
 
Cytokines and their role in immune regulation.pptx
Cytokines and their role in immune regulation.pptxCytokines and their role in immune regulation.pptx
Cytokines and their role in immune regulation.pptx
 
NuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyerNuGOweek 2024 Ghent programme overview flyer
NuGOweek 2024 Ghent programme overview flyer
 
Describing and Interpreting an Immersive Learning Case with the Immersion Cub...
Describing and Interpreting an Immersive Learning Case with the Immersion Cub...Describing and Interpreting an Immersive Learning Case with the Immersion Cub...
Describing and Interpreting an Immersive Learning Case with the Immersion Cub...
 
Phenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvementPhenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvement
 

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