58
Reproducible reports with Markdown, knitr Mikhail Dozmorov Summer 2018 Mikhail Dozmorov Reproducible reports with Markdown, knitr Summer 2018 1 / 58

Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Reproducible reports with Markdown knitr

Mikhail Dozmorov

Summer 2018

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 1 58

Literate programming

Let us change our traditional attitude to the construction of programsInstead of imagining that our main task is to instruct a computer what todo let us concentrate rather on explaining to humans what we wantthe computer to do

ndash Donald E Knuth Literate Programming 1984

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 2 58

Name to know Edward TufteldquoDesign cannot rescue failed contentrdquo

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 3 58

Tuftersquos Rules

1 Show the data2 ldquoInduce the viewer to think about the substance rather than about

methodology graphic design the tech of graphic production orsomething elserdquo

3 Avoid Distorting the Data4 Present Many Numbers in a Small Space5 Make Large Datasets Coherent6 Encourage Eyes to Compare Data7 Reveal Data at Several Levels of Detail8 Serve a Reasonably Clear Purpose9 Be Closely Integrated with Statistical and Verbal Descriptions of the

Dataset

httpwwwsealthreinholdcomschooltuftes-rulesrule_onephp

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 4 58

Document formatting

Document formatting

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 5 58

Document formatting

Writing reports

HTML - HyperText Markup Language used to create web pagesDeveloped in 1993LaTeX ndash a typesetting system for production of technicalscientificdocumentation PDF output Developed in 1994Sweave ndash a tool that allows embedding of the R code in LaTeXdocuments PDF output Developed in 2002Markdown ndash a lightweight markup language for plain text formattingsyntax Easily converted to HTML

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 6 58

Document formatting

HTML example

HTML files have htm or html extensionsPairs of tags define contentformatting

lth1gt Header level 1 lth1gtlta href=ldquohttpwwwrdquogt Link ltagtltpgt Paragraph ltpgt

ltDOCTYPE htmlgtlthtmlgtltheadgtltmeta http-equiv=Content-Type content=texthtml charset=utf-8gtltheadgt

ltbodygtlth1gtMarkdown examplelth1gt

ltpgtThis is a simple example of a Markdown documentltpgt

You can emphasize code with ltstronggtboldltstronggt or ltemgtitalicsltemgt or ltcodegtmonospaceltcodegt fontltbodygtlthtmlgt

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 7 58

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 2: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Literate programming

Let us change our traditional attitude to the construction of programsInstead of imagining that our main task is to instruct a computer what todo let us concentrate rather on explaining to humans what we wantthe computer to do

ndash Donald E Knuth Literate Programming 1984

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 2 58

Name to know Edward TufteldquoDesign cannot rescue failed contentrdquo

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 3 58

Tuftersquos Rules

1 Show the data2 ldquoInduce the viewer to think about the substance rather than about

methodology graphic design the tech of graphic production orsomething elserdquo

3 Avoid Distorting the Data4 Present Many Numbers in a Small Space5 Make Large Datasets Coherent6 Encourage Eyes to Compare Data7 Reveal Data at Several Levels of Detail8 Serve a Reasonably Clear Purpose9 Be Closely Integrated with Statistical and Verbal Descriptions of the

Dataset

httpwwwsealthreinholdcomschooltuftes-rulesrule_onephp

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 4 58

Document formatting

Document formatting

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 5 58

Document formatting

Writing reports

HTML - HyperText Markup Language used to create web pagesDeveloped in 1993LaTeX ndash a typesetting system for production of technicalscientificdocumentation PDF output Developed in 1994Sweave ndash a tool that allows embedding of the R code in LaTeXdocuments PDF output Developed in 2002Markdown ndash a lightweight markup language for plain text formattingsyntax Easily converted to HTML

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 6 58

Document formatting

HTML example

HTML files have htm or html extensionsPairs of tags define contentformatting

lth1gt Header level 1 lth1gtlta href=ldquohttpwwwrdquogt Link ltagtltpgt Paragraph ltpgt

ltDOCTYPE htmlgtlthtmlgtltheadgtltmeta http-equiv=Content-Type content=texthtml charset=utf-8gtltheadgt

ltbodygtlth1gtMarkdown examplelth1gt

ltpgtThis is a simple example of a Markdown documentltpgt

You can emphasize code with ltstronggtboldltstronggt or ltemgtitalicsltemgt or ltcodegtmonospaceltcodegt fontltbodygtlthtmlgt

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 7 58

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 3: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Name to know Edward TufteldquoDesign cannot rescue failed contentrdquo

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 3 58

Tuftersquos Rules

1 Show the data2 ldquoInduce the viewer to think about the substance rather than about

methodology graphic design the tech of graphic production orsomething elserdquo

3 Avoid Distorting the Data4 Present Many Numbers in a Small Space5 Make Large Datasets Coherent6 Encourage Eyes to Compare Data7 Reveal Data at Several Levels of Detail8 Serve a Reasonably Clear Purpose9 Be Closely Integrated with Statistical and Verbal Descriptions of the

Dataset

httpwwwsealthreinholdcomschooltuftes-rulesrule_onephp

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 4 58

Document formatting

Document formatting

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 5 58

Document formatting

Writing reports

HTML - HyperText Markup Language used to create web pagesDeveloped in 1993LaTeX ndash a typesetting system for production of technicalscientificdocumentation PDF output Developed in 1994Sweave ndash a tool that allows embedding of the R code in LaTeXdocuments PDF output Developed in 2002Markdown ndash a lightweight markup language for plain text formattingsyntax Easily converted to HTML

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 6 58

Document formatting

HTML example

HTML files have htm or html extensionsPairs of tags define contentformatting

lth1gt Header level 1 lth1gtlta href=ldquohttpwwwrdquogt Link ltagtltpgt Paragraph ltpgt

ltDOCTYPE htmlgtlthtmlgtltheadgtltmeta http-equiv=Content-Type content=texthtml charset=utf-8gtltheadgt

ltbodygtlth1gtMarkdown examplelth1gt

ltpgtThis is a simple example of a Markdown documentltpgt

You can emphasize code with ltstronggtboldltstronggt or ltemgtitalicsltemgt or ltcodegtmonospaceltcodegt fontltbodygtlthtmlgt

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 7 58

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 4: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Tuftersquos Rules

1 Show the data2 ldquoInduce the viewer to think about the substance rather than about

methodology graphic design the tech of graphic production orsomething elserdquo

3 Avoid Distorting the Data4 Present Many Numbers in a Small Space5 Make Large Datasets Coherent6 Encourage Eyes to Compare Data7 Reveal Data at Several Levels of Detail8 Serve a Reasonably Clear Purpose9 Be Closely Integrated with Statistical and Verbal Descriptions of the

Dataset

httpwwwsealthreinholdcomschooltuftes-rulesrule_onephp

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 4 58

Document formatting

Document formatting

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 5 58

Document formatting

Writing reports

HTML - HyperText Markup Language used to create web pagesDeveloped in 1993LaTeX ndash a typesetting system for production of technicalscientificdocumentation PDF output Developed in 1994Sweave ndash a tool that allows embedding of the R code in LaTeXdocuments PDF output Developed in 2002Markdown ndash a lightweight markup language for plain text formattingsyntax Easily converted to HTML

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 6 58

Document formatting

HTML example

HTML files have htm or html extensionsPairs of tags define contentformatting

lth1gt Header level 1 lth1gtlta href=ldquohttpwwwrdquogt Link ltagtltpgt Paragraph ltpgt

ltDOCTYPE htmlgtlthtmlgtltheadgtltmeta http-equiv=Content-Type content=texthtml charset=utf-8gtltheadgt

ltbodygtlth1gtMarkdown examplelth1gt

ltpgtThis is a simple example of a Markdown documentltpgt

You can emphasize code with ltstronggtboldltstronggt or ltemgtitalicsltemgt or ltcodegtmonospaceltcodegt fontltbodygtlthtmlgt

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 7 58

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 5: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Document formatting

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 5 58

Document formatting

Writing reports

HTML - HyperText Markup Language used to create web pagesDeveloped in 1993LaTeX ndash a typesetting system for production of technicalscientificdocumentation PDF output Developed in 1994Sweave ndash a tool that allows embedding of the R code in LaTeXdocuments PDF output Developed in 2002Markdown ndash a lightweight markup language for plain text formattingsyntax Easily converted to HTML

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 6 58

Document formatting

HTML example

HTML files have htm or html extensionsPairs of tags define contentformatting

lth1gt Header level 1 lth1gtlta href=ldquohttpwwwrdquogt Link ltagtltpgt Paragraph ltpgt

ltDOCTYPE htmlgtlthtmlgtltheadgtltmeta http-equiv=Content-Type content=texthtml charset=utf-8gtltheadgt

ltbodygtlth1gtMarkdown examplelth1gt

ltpgtThis is a simple example of a Markdown documentltpgt

You can emphasize code with ltstronggtboldltstronggt or ltemgtitalicsltemgt or ltcodegtmonospaceltcodegt fontltbodygtlthtmlgt

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 7 58

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 6: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Writing reports

HTML - HyperText Markup Language used to create web pagesDeveloped in 1993LaTeX ndash a typesetting system for production of technicalscientificdocumentation PDF output Developed in 1994Sweave ndash a tool that allows embedding of the R code in LaTeXdocuments PDF output Developed in 2002Markdown ndash a lightweight markup language for plain text formattingsyntax Easily converted to HTML

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 6 58

Document formatting

HTML example

HTML files have htm or html extensionsPairs of tags define contentformatting

lth1gt Header level 1 lth1gtlta href=ldquohttpwwwrdquogt Link ltagtltpgt Paragraph ltpgt

ltDOCTYPE htmlgtlthtmlgtltheadgtltmeta http-equiv=Content-Type content=texthtml charset=utf-8gtltheadgt

ltbodygtlth1gtMarkdown examplelth1gt

ltpgtThis is a simple example of a Markdown documentltpgt

You can emphasize code with ltstronggtboldltstronggt or ltemgtitalicsltemgt or ltcodegtmonospaceltcodegt fontltbodygtlthtmlgt

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 7 58

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 7: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

HTML example

HTML files have htm or html extensionsPairs of tags define contentformatting

lth1gt Header level 1 lth1gtlta href=ldquohttpwwwrdquogt Link ltagtltpgt Paragraph ltpgt

ltDOCTYPE htmlgtlthtmlgtltheadgtltmeta http-equiv=Content-Type content=texthtml charset=utf-8gtltheadgt

ltbodygtlth1gtMarkdown examplelth1gt

ltpgtThis is a simple example of a Markdown documentltpgt

You can emphasize code with ltstronggtboldltstronggt or ltemgtitalicsltemgt or ltcodegtmonospaceltcodegt fontltbodygtlthtmlgt

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 7 58

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 8: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

LaTeX example

LaTeX files usually have a tex extensionLaTeX commands define appearance of text and other formattingstructures

documentclassarticleusepackagegraphicx

begindocument

titleIntroduction to LaTeXauthorAuthors Name

maketitle

beginabstractThis is abstract text This simple document shows very basic features ofLaTeXendabstract

sectionIntroductionhttpwwwelectronicsoulufilatexexamplesexample_1

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 8 58

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 9: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Sweave example

Sweave files typically have an Rnw extensionLaTeX syntax for text ltltchunk_namegtgt= ltcodegt syntax outlinescode blocks

documentclassarticle

usepackageamsmath

usepackagenatbibusepackageindentfirst

DeclareMathOperatorlogitlogit

VignetteIndexEntryLogit-Normal GLMM Examples

begindocument

First we attach the dataltltboothgtgt=library(bernor)data(booth)attach(booth)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 9 58

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 10: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Markdown

Markdown is a markup language like HTML and LaTeX but designedto be as lightweight as possibleThe goal is still to separate form and content but also to prioritizehuman-readability even at the cost of fancy featuresYou can learn Markdown in about 5 minutes If you can write an emailyou can write MarkdownOr use a desktop Markdown editor like MarkdownPad (Windows) orMacDown (Mac)

httpbioconnectorgithubiomarkdown

httpmarkdownpadcom

httpmacdownuranusjrcom

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 10 58

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 11: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Basic Markdown Syntax

Regardless of your chosen output format some basic syntax will be useful

Section headersText emphasisListsR code

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 11 58

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 12: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Section Headers

To set up different sized header text in your document use for Header 1 for Header 2 and for Header 3

In a presentation this creates a new slide

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 12 58

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 13: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Text emphasis

Italicize text via Italicize or _Italicize_Bold text via Bold or __Bold__

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 13 58

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 14: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Unordered Lists

This code

Item 1 Item 2

+ Item 2a+ Item 2b

Renders these bullets (sub-lists need 1 tab or 4 spaces)

Item 1Item 2

Item 2aItem 2b

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 14 58

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 15: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Ordered ListsThis code

1 Item 12 Item 2

+ Item 2a+ Item 2b

Renders this list (be advised - the bullets may not look great in alltemplates)

1 Item 12 Item 2

Item 2aItem 2bMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 15 58

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 16: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Inline R Code

To use R within a line use the syntax wrapped in single forward ticksr dim(mtx)This can be useful to refer to estimates confidence intervals p-valuesetc in the body of an articlehomework without worrying about copyerrors

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 16 58

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 17: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Markdown syntax

superscript^2^~~strikethrough~~

Linkshttpexamplecom[linked phrase](httpexamplecom)

Images[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

BlockquotesA friend once saidgt Its always better to givegt than to receive

Horizontal Rule Page Break------

Tables

First Header | Second Header------------- | -------------Content Cell | Content CellContent Cell | Content Cell

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 17 58

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 18: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Large code chunks

Marked with triple backticks

```r optionalChunkName echo=TRUE results=hide R code here```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 18 58

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 19: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Creating R markdown document

Regular text file with Rmd extensionCreate manually or use RStudio

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 19 58

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 20: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

YAML header (think settings)

YAML - YAML Ainrsquot Markup LanguageYAML is a simple text-based format for specifying data like JSON

---title Untitledauthor rdquoYour Namedate rdquoCurrent dateoutput html_document---

output is the critical part ndash it defines the output format Can bepdf_document or word_documenthttpsgithubcommdozmorovMDmisc

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 20 58

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 21: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

YAML header for a PDF presentation

---title Reproducible reports with Markdown knitrauthor Mikhail Dozmorovdate Summer 2018outputbeamer_presentation colortheme seahorsecolortheme dolphinfig_caption nofig_height 6fig_width 7fonttheme structurebold theme boxestheme AnnArbor

---Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 21 58

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 22: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

YAML header for a Word document

---bibliography [3D_refsbibbrainbib]csl stylesrefgenomebiologycsloutputword_documentreference_docx stylesdocNIH_grant_styledocx

pdf_document defaulthtml_document default

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 22 58

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 23: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Modifying the behavior of R code chunksChunk options comma-separated

echo=FALSE - hides the code but not the resultsoutput DefaultTRUEresults=lsquohidersquo - hides the resultsoutput markup (the default)takes the result of the R evaluation and turns it into markdown that isrendered as usual hold ndash hold will hold all the output pieces andpush them to the end of a chunk Useful if yoursquore running commandsthat result in lots of little pieces of output in the same chunk hidewill hide results asis writes the raw results from R directly into thedocument Only really useful for tableseval=FALSE - disables code execution Default TRUEcache=TRUE - turn on caching of calculation-intensive chunk DefaultFALSEfigwidth= figheight= - customize the size of a figuregenerated by the code chunkinclude (TRUE by default) if this is set to FALSE the R code is stillevaluated but neither the code nor the results are returned in theoutput document

The full list of options httpyihuinameknitroptions

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 23 58

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 24: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Global chunk options

Some options you would like to set globally instead of typing them foreach chunk

knitropts_chunk$set(figwidth=12 figheight=8 figpath=imgrsquo cachepath=cache cache=FALSE echo=FALSE warning=FALSE message=FALSE)

warning=FALSE and message=FALSE suppress any R warnings ormessages from being included in the final documentfigpath=img - the figure files get placed in the img subdirectory(Default not saved at all)

A special note about caching The cache= option is automatically set toFALSE That is every time you render the Rmd all the R code is run againfrom scratch If you use cache=TRUE for this chunk knitr will save theresults of the evaluation into a directory that you specify egcachepath=cache When you re-render the document knitr willfirst check if there are previously cached results under the cache directorybefore really evaluating the chunk if cached results exist and this codechunk has not been changed since last run (use MD5 sum to verify) thecached results will be (lazy-) loaded otherwise new cache will be built if acached chunk depends on other chunks (see the dependson option) andany one of these chunks has changed this chunk must be forcibly updated(old cache will be purged) See the documentation for caching

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 24 58

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 25: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

An example of R Markdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 25 58

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 26: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

KnitR

KnitR ndash Elegant flexible and fast dynamic report generation writtenin R Markdown PDF HTML DOCX output Developed in 2012

installpackages(knitr dependencies = TRUE)

httpsgithubcomyihuiknitr httpyihuinameknitr

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 26 58

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 27: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Displaying data as tables

KnitR has built-in function to display a table

data(mtcars)knitrkable(head(mtcars))

pander package allows more customization

panderpander(head(mtcars))

xtable package has even more options

xtablextable(head(mtcars))

DT package an R interface to the DataTables library

DTdatatable(mtcars)httpbioconnectorgithubiomarkdownrmarkdownmdPrinting_tables_nicely

httpscranr-projectorgwebpackagesxtablevignettesxtableGallerypdf

httpscranr-projectorgwebpackageskableExtravignettesawesome_table_in_htmlhtml

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 27 58

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 28: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Including figures

Plots may be generated by R code and displayed in the outputdocumentExisting image files like jpg png may be inserted like

[](httpexamplecomlogopng)[optional caption text](figuresimgpng)

Alternatively use knitr capabilitiesr outwidth = 300px echo=FALSEknitrinclude_graphics(imgbandThree2png)For PDF output use LaTeX syntax

begincenterincludegraphics[height=170px]imgbioinfo3pngendcenter

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 28 58

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 29: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Customizing Figures Captions

The figcap option allows you to specify the caption for the figuregenerated by a given chunk

```r caption figcap=I am the captionplot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 29 58

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 30: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Customizing Figures Size

The figheight and figwidth options let you specify the dimensions ofyour plots

```r caption figheight = 4 figwidth = 8plot(pressure)```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 30 58

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 31: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Creating the final report

Markdown documents (md or Rmd) can be converted to HTMLusing markdownmarkdownToHTML(markdown_examplemdmarkdown_examplehtml)Another option is to usermarkdownrender(markdown_examplemdrsquo) At the backend ituses pandoc command line tool installed with RstudioRstudio ndash one button knit2html() knit2pdf() functions

Note KnitR compiles the document in an R environment separate fromyours (think Makefile) Do not use Rprofile file - it loads into yourenvironment onlyhttppandocorg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 31 58

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 32: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Things to include in your final report

setseed(12345) ndash initialize random number generator

Include session_info() at the end ndash outputs all packagesversions used

```r sessionInfodiagnostics lt- devtoolssession_info()platform lt- dataframe(diagnostics$platform gt unlist stringsAsFactors = FALSE)colnames(platform) lt- c(description)pander(platform)packages lt- asdataframe(diagnostics$packages)pander(packages[ packages$`` == ])```

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 32 58

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 33: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Making default RMarkdown document on your own

Altering the default Rmarkdown file each time you write a homeworkreport or article would be a pain

Fortunately you donrsquot have to

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 33 58

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 34: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Templates

You can create your own templates which set-up packages fonts defaultchunk options etc

httprmarkdownrstudiocomdeveloper_document_templateshtmlSome packages (eg rticles) provide templates that meet journalrequirements or provide other

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 34 58

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 35: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Document formatting

Parameters

You may also set parameters in your documentrsquos YAML header

---output html_documentparamsdate 2017-11-02

---

or pass new values with the render function

This creates a read-only list params containing the values declaredeg params$date returns 2017-11-02

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 35 58

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 36: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Bibliography

Bibliography

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 36 58

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 37: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Bibliography

BibTex

articleBerkum2010aaAbstract = The three-dimensional folding of chromosomes Author = van Berkum Nynke L and Lieberman-Aiden Erez and Williams Louise and Imakaev Maxim and Gnirke Andreas and Mirny Leonid A and Dekker Job and Lander Eric SDate-Added = 2016-10-08 142623 +0000Date-Modified = 2016-10-08 142623 +0000Doi = 1037911869Journal = J Vis ExpJournal-Full = Journal of visualized experiments JoVEMesh = Chromosome Positioning Chromosomes DNA Genomics Nucleic Acid ConformationNumber = 39Pmc = PMC3149993Pmid = 20461051Pst = epublishTitle = Hi-C a method to study the three-dimensional architecture of genomesYear = 2010Bdsk-Url-1 = httpdxdoiorg1037911869Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 37 58

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 38: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Bibliography

BibTex managers

JabRef for Windows httpwwwjabreforgBibDesk for Mac httpbibdesksourceforgenet

Save references in bib text file

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 38 58

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 39: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Bibliography

Convert anything to BibTex

doi2bib - BibTex from DOI arXiv biorXiv httpswwwdoi2biborgZoteroBib - create a bibliography from a URL ISBN DOI PMIDarXiv ID or title Download as BibTex and more httpszbiborg

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 39 58

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 40: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Bibliography

BibTex and RMarkdown

Add to YAML header

bibliography 3D_refsbib

Insert into RMarkdown as

The 3D structure of the human genome has proven to be highly organized[Dixon2012aa Rao2014aa] This organization starts from distinctchromosome territories [Cremer2010aa] following by topologically associateddomains (TADs) [Dixon2012aa Jackson1998aa Ma1998aa Nora2012aa Sexton2012aa]smaller sub-TADs [Phillips-Cremins2013aa Rao2014aa] and on themost local level individual regions of interacting chromatin [Rao2014aa Dowen2014aa Ji2016aa]

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 40 58

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 41: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Bibliography

Format your BibTex references

Add to YAML header

csl genomebiologycsl

Get more styles at httpswwwzoteroorgstyles

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 41 58

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 42: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Bibliography

Format your Word output

If knitting into Word output you may want to have fonts headersmargins other than defaultCreate a Word document with the desired formatting Change fontstyles by right-clicking on the font (eg ldquoNormalrdquo) and select ldquoModifyrdquoInclude it into YAML header

outputword_documentreference_docx stylesdocNIH_grant_styledocx

httpsgithubcommdozmorovpresentationstreemasterioslides_template

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 42 58

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 43: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Math formulas

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 43 58

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 44: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Markdown Code MathJax

Markdown supports MathJax JavaScript engine to rendermathematical equations and formulasInline equations - use single ldquodollar signrdquo $ to specify MathJax coding

$s^2 = fracsum(x-barx)^2n-1$

s2 =sum

(xminusx)2nminus1

Check out this online tutorial httpmetamathstackexchangecomquestions5020mathjax-basic-tutorial-and-quick-reference

httpsgithubcomohsu-knight-cancer-biostatisticsreproducible-researchblob32bba6a78e347d64745982fb6245915cecb1b7c3slides-info-reproducible-researchstudy-group-2016Chpt201320Web20PresentationsMathJax_2Rmd

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 44 58

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 45: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Centering you equations

Insertion of two dollar signs $$ centers your equations Other examples offset and centered - notice double dollar signs

$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $

$$ sum_i=0^n i^2 = frac(n^2+n)(2n+1)6 $$

Inline equationsumn

i=0 i2 = (n2+n)(2n+1)6 on the same line Or self-standing

equation on a separate linensum

i=0i2 = (n2 + n)(2n + 1)

6

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 45 58

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 46: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

More Interesting Codes

Greek Letters

$alpha$ $beta$ $gamma$ $chi$$Delta$ $Sigma$ $Omega$

Greek Letters (not all capitalized Greek letters available)

α β γ χ

∆ Σ Ω

superscripts (ˆ) and subscripts (_)

x2i log2x

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 46 58

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 47: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Grouping with Brackets

Use brackets to delimit a formula containing a superscript orsubscript Notice the difference the grouping makes

$x^y^z$$x^y^z$$x_i^2$$x_i^2$

xy z xy z x2i xi2

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 47 58

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 48: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Scaling

Add the scaling code left(right) to make automatic sizeadjustments

$(fracsqrt xy^3)$$left(fracsqrt xy^3right)$

(radic

xy3 )

(radicx

y3

)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 48 58

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 49: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Sums and Integrals

Subscript (_) designates the lower limit superscript (ˆ) designates upperlimit

$sum_1^n$ $sum_i=0^infty i^2$

sumn1suminfin

i=0 i2

Other notable symbols

- $prod$ $infty$- $bigcup$ $bigcap$- $int$ $iint$

prodinfin⋃ ⋂ int intintMikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 49 58

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 50: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Radical Signs

Use lsquosqrtrsquo code to adjust the size of its argument Note the change in sizeof the square root function based on the code

1 $sqrtx^3$2 $sqrt[3]frac xy$and for complicated expressions use brackets

3 $^12$

1radic

x3

2 3radic

xy

3 12

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 50 58

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 51: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

You can also change fonts

$mathbb or $Bbb for Blackboard bold$mathbf for boldface$mathtt for typewritter font$mathrm for roman font$mathsf for sans-serif$mathcal for caligraphy$mathscr for script letter$mathfrak for Fraktur (old German style)

ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG ABCDEFG

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 51 58

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 52: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

You can also change fonts

Some special functions such as ldquolimrdquo ldquosinrdquo ldquomaxrdquo and ldquolnrdquo are normally setin roman font instead of italic Use lim sin to make these (roman)

$sin x$ (roman) vs $sin x$ (italics)

sin x (roman) vs sinx (italics)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 52 58

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 53: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

And add curly brackets

$$begincaseswidehatIF_1D = IF_1D - f(D)2 widehatIF_2D = IF_2D + f(D)2endcases (1)$$

IF1D = IF1D minus f (D)2IF2D = IF2D + f (D)2(1)

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 53 58

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 54: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

RStudio bonusInline preview of forumlas and images in an RMarkdown document

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 54 58

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 55: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

LATEX and Markdown

Rendering Markdown as a pdf requires a LATEX installationYou will additionally need to install Pandoc from httppandocorgWith LATEX many customizations are possible

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 55 58

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 56: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

LATEX Customization 1

You can include additional LATEX commands and contentUse the includes option as follows to add your favorite style files forthe preamble titleabstract bibliography etc

---title A More Organized Persons Documentoutputbeamer_presentationincludesin_header headertexbefore_body doc_prefixtexafter_body doc_suffixtex

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 56 58

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 57: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

LATEX Customization 2

If you prefer a self-contained document you may opt for theheader-includes option over the modular approach

---title BIOST 691 Reproducible Research Toolsauthor Author Namedate November 2 2017header-includes

- usepackagegraphicxoutputbeamer_presentationtheme Frankfurt

---

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 57 58

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas
Page 58: Reproducible reports with Markdown, knitrTufte’sRules 1 Showthedata 2 “Inducetheviewertothinkaboutthesubstanceratherthanabout methodology,graphicdesign,thetechofgraphicproduction,or

Math formulas

Note LATEXin Text

In Markdown ldquoLaTeX rocksrdquo renders as ldquoLATEXrocksrdquo (no space)Use ldquoLaTeX rocksrdquo to render ldquoLATEX rocksrdquo insteadThis can be especially important when using new commands

Mikhail Dozmorov Reproducible reports with Markdown knitr Summer 2018 58 58

  • Document formatting
  • Bibliography
  • Math formulas