R Markdown Cheat Sheet f ® learn more at rmarkdown.rstudio.com {^Studio .Rmd files An R Markdown (.Rmd) file is a record of your research. It contains the code that a scientist needs to reproduce your work alongwith the narration that a reader needs to understand yourwork. —r Reproducible Research At the click of a button, or the type of a command, you can rerun the code in an R Markdown file to reproduceyourworkand export the results as a finished report. CO Dynamic Documents You can choose to export the finished report as a html, pdf, MSWord,ODT, RTF, or markdown document; oras a html or pdf based slide show. Workflow IOpen a new .Rmd file at File ► New File ► R Markdown. Use the wizard that opens to pre-populatethefile with a template Open in I Save Spell windowl ; Check Knit document to create report A Preview Output Use knit button or renderQ to knit ■ inlDEwindow YAML Header Optional section of render (e.g. pandoc) options written as key:value pairs (YAML). • At start of file • Between lines of — Text ................ Narration formatted with markdown, mixed with: Code chunks .... Chunks of embedded code. Each chunk: • Begins with • ends with R Markdown will run the code and append the results to the doc. It will use the location of the .Rmd file asthe working directory Publish (optional) to web or server Synch publish button to accounts at • rpubs.com. • shinyapps.io • RStudio Connect Reload document Find in document File path to output document 6Examine build log in R Markdown console *W Use output file that is * saved alongside .Rmd Inline code I nsert with ' r '. Resu Its a ppea r as text without code. Embed code with knitr syntax Code chunks Built with 'r getRversionf) ' Built with 3.2.3 One or more lines surrounded with '{r} and '''. Place chunk options within curly braces, after r. Insert with " ""{r echo=TRUE> getRversionf) renderQ Use rmarkdown::render() to render/knit at cmd line, m porta nt args: input - file to render output_format output_options - List of render options (as in YAML) output_file output_dir params - list of pa ra ms to use envir- environmentto evaluate code chunks in encoding - of input file Global options Set with knitr::opts_chunk$set(), e.g. Important chunk options " '{r include=FALSE} knitr::opts_chunk$set(echo = TRUE) cache - cache resu Its for future knits (default = FALSE) cache.path - directory to save cached results in (default = "cache/") child - file(s) to knit and then include (default= NULL) collapse - collapse all output into single block (default = FALSE) comment - prefix for each line of results (default = '##') Options not listed above: R.options, aniopts, fig.lp, fig.path, fig.pos, fig.process, fig.retina, dependson - chunk dependencies for caching (default= NULL) echo - Display code in output document (default = TRUE) engine - code language used in chunk (default = 'R') error- Display error messages in doc (TRUE) orstop render when errorsoccur (FALSE) (default = FALSE) eval- Run code in chunk (default = TRUE) fig.align - 'left1, 'right1, or 'center' (default ='default') fig.cap - figure caption as character string (default = NULL) fig.height, fig.width - Dimensions of plots in inches highlight - highlight source code (default = TRUE) include - Includechunkindoc after running (default = TRUE) message - display code messages in document(default = TRUE) results (default = 'markup') asis' - passthrough results hide' - do not display results hold' - put all results below all code tidy-tidy code for display (default = FALSE) warning - display code warnings in document(default = TRUE) Interactive Documents Turn your report into an interactive Shiny document in 4 steps Add runtime: shiny to the YAML header. Call Shiny input functions to embed input objects. Call Shiny render functions to embed reactive output. Render with rmarkdown::run or click Run Document in RStudio IDE output: html_document runtime: shiny '"{r, echo = FALSE} numericlnput("n", "How many cars?", 5) renderTable({ head(cars, input$n) How many cars? 5 : speed dist 1 4.00 2.00 2 4 .00 10.00 3 7.00 4.00 4 7.00 22.00 5 8.00 16.00 Embed a complete app into your document with shiny::shinyAppDir() * Your report will rendered as a Shiny app, which means you must choose an html output format, like html_document, and serve It with an active R Session. Parameters Parameterize your documents to reuse with different inputs (e.g., data sets, values, etc.) Add parameters Create and set parameters in the header as sub-values of params params: n: 100 d: !r Sys.DateQ Today's date is 'r params$d' □ C\ Knit HTML - autodep, background, cache.comments, cache.lazy, cache.rebuild, cache.vars, dev, dev.args, dpi, engine.opts, engine.path, fig.asp, fig.env, fig.ext, fig.keep, fig.scap, fig.show, fig.showtext, fig.subcap, interval, out.extra, out.height, out.widtn, prompt, purl, rer.label, render, size, split, tidy.opts Call parameters Call parameter values in code as params$ Set parameters Set values wth Knit with parameters or the params argument of render)): render("doc.Rmd", params = list(n = 1, d = as.Date("2015-01-01")) Knit to HTML Knit to PDF Knit to Word Knit with Parameters... RStudio® is a trademark of RStudio, Inc. • CC BY RStudio ■ info(5)rstudio.com • 844-448-1212 ■ rstudio.com More Cheatsheets at http://www.rstudio.com/resources/cheatsheets/ Learnmoreatrmarkdown.rstudio.com • RStudio IDE 0.99.879 • Updated: 02/16 Pandoc's Markdown Set render options with YAML Write with syntax on the left to create effect on right (after render] Plain text End a line with two spaces to start a new paragraph. ^italics* and **bold** 'verbatim code' sub/superscriptA2A~2~ —stri kethrough— escaped: \* \_ \\ endash: —, emdash: --- equation: $A - \pi*rA{2}$ equation block: $$E - mcA{2}$$ > block quote # Headerl {#anchor} ## Header 2 {#css_id} ### Header 3 {.css_class} #### Header 4 ##### Header 5 ###### Header 6 Plain text End a line with two spaces to start a new paragraph. italics and bold verbatim code sub/su person pt22 strikethrough escaped: * _\ endash: -, emdash: — equation: A = n * r2 equation block: E = mc2 block quote Headerl Header 2 \textbf{Tex ignored in HTML} HTML ignored in pdfs [li nk](www.rstudio.com) Jump to [Header 1](#anchor) image: ! [Caption](smallorb.png) * unordered list + sub-item 1 + sub-item 2 - sub-sub-item 1 * item 2 Continued (indent 4 spaces) 1. ordered list 2. item 2 i) sub-item 1 A. sub-sub-item 1 Header 3 Header 4 Header 5 Header 6 HTML ignored in pdfs http://www.rstudio.com link Jump to Header 1 image: Caption • unordered list o sub-item 1 o sub-item 2 ■ sub-sub-item 1 * item 2 Continued (indent 4 spaces) 1. ordered list 2. item 2 i. sub-item 1 A. sub-sub-item 1 1. A list whose numbering (@) A list Whose numbering continues after 2. an interruption Term 1 continues after (@) an interruption Term 1 : Definition 1 Definition 1 Right Left Default Center Right I Left | Default Center | 12 12 12 12 12 J 12 j 12 12 j 123 123 123 123 123 j 123 j 123 123 j 1 j 1 j 1 1 j 11 1 1 slide bullet 1 • slide bullet 1 slide bullet 2 • slide bullet 2 (>- to have bullets appear on click) horizontal rule/slide break: *** A footnote [Al] [Al]: Here is the footnote. (>- to have bullets appear on click) horizontal rule/slide break: When you render, R Markdown 1. runs the R code, embeds results and text into .md file with knitr 2. then converts the .md file into the finished format with pandoc I ^ J knitr j md I j] Set a document's default output format in the YAML header: output: html_document # Body output value html_document pdf_docu merit word_document odt_document rtf_document md_docu merit github_document ioslides_presentation slidy_presentation beamer_presentation Customize output with sub-options (listed at right): html tabsets Use .tabset ess class to place sub-headers into tabs creates html pdf (requires Tex) Microsoft Word (.docx) OpenDocument Text Rich Text Format Markdown Github compatible markdown ioslides HTML slides slidy HTML slides Beamer pdf slides (requires Tex) I Indent2 Indent 4 1 j spaces spaces J output: html_document: T code_folding: hide toc_float: TRUE # Body # Tabset {.tabset .tabset-fade . tabset-pills} tttt Tab 1 text 1 Tabset tttt Tab 2 text 2 tttttt End tabset 1 Tab1 1 1 text 1 End tabset Create a Reusable template Create a new package with a inst/rmarkdown/templates directory In the directory, Place a folder that contains: template.yaml (see below) skeleton.Rmd (contents of the template) anysupportingfiles Install the package Access template in wizard at File > New File ► R Markdown template.yaml 1. Here is the footnote.*-1 name: My Template citation_package The LaTeX package to process citations, natblb, blblatex or none code_folding Let readers to toggle the display of R code, "none", "hide", or "show" colortheme Beamer color theme to use ess CSS file to use to style document dev Graphics device to use for figure output (e.g. "png") duration Add a countdown timer (in minutes) to footer of slides fig_caption Should figures be rendered with captions? figjieight, fig_width Default figure height and width (in inches) for document highlight Syntax highlighting: "tango", "pygments", "kate","zenburn", "textmate" includes File of content to place in document (in_header, before_body, after_body) incremental Should bullets appear one at a time (on presenter mouse clicks)? keep_md Save a copy of .md file that contains knitr output keep_tex Save a copy of .tex file that contains knitr output latex_engine Engine to render latex, "pdflatex", "xelatex", or "lualatex" lib_dir Directory of dependency files to use (Bootstrap, MathJax, etc.) mathjax Set to local or a URL to use a local/URL version of MathJax to render md_extensions Markdown extensions to add to default definition or R Markdown number_sections Add section numbering to headers pandoc_args Additional arguments to pass to Pandoc preserve_yaml Preserve YAML front matter in final document? reference_docx docx file whose styles should be copied when producing docx output self_contained Embed dependencies into the doc slide_level The lowest heading level that defines individual slides smaller Use the smaller font size in the presentation? smart Convert straight quotes to curly, dashes to em-dashes,... to ellipses, etc. template Pandoc template to use when rendering file theme Bootswatch or Beamer theme to use for page toe Add a table of contents at start of document toc_depth The lowest level of headings to add to table of contents toc_float Float the table of contents to the left of the main content Options not listed X X X X XXX X X X X X xxxxxxxx XXX X XXX X XXX X X X X X X X X xxxxxxxx X X xxxxxxxx X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X XXX XXX X X X XXX XXX X X X X X extra_dependencies, fig_crop, fig_retina, font_adjustment, font_theme, footer, logo, htmLpreview, reference_odt, transition, variant, widescreen Table suggestions Several functions format R data into tables Table with stargazer 3.333 ■ I ■ eruptions waiting 1 3.60 79.00 2 1.80 54.00 3 3.33 74.00 4 2.28 62.00 Table with xtable erupt ionswaiting 1 3.600 79~ 2 1.800 54 3 3.333 74 4 2.283 62 Citations and Bibliographies Create citations with .bib, .bibtex, .copac, .enl, .json, .medline, .mods, .ris, .wos, and .xml files Set bibliography file and CSL 1.0 Style file (optional) in the YAML header data<-faithful[l:4, ] ''' {r results = 'asis'} knitr::kable(data, caption = "Table with kable") ''' {r results = "asis"} print(xtable::xtable(data, caption = "Table with xtable"),I type = "html", html.table.attributes = "border=0")) ' ' {r results = "asis"} Learn more in stargazer::stargazer(data, type = "html", the stargazer, xtable, and knitr packages. bibliography: refs.bib csl: style.csl Use citation keys in text Smith cited [@smith04]. Smith cited without author [-@smith04]. @smith04 cited in line. Render. Bibliography will beadded to end of document title = "Table with stargazer") Smith cited (Joe Smith 2004). Smith cited without author (2004). Joe Smith (2004) cited in line. RStudio® is a trademark of RStudio, Inc. • CC BY RStudio ■ info(5)rstudio.com • 844-448-1212 ■ rstudio.com More Cheatsheets at http://www.rstudio.com/resources/cheatsheets/ Learnmoreatrmarkdown.rstudio.com • RStudio IDE 0.99.879 • Updated: 02/16