R Markdown What is R Markdown? : : CHEATSHEET -—File path to output document # 0 ~/Desktop/R-Markdown-Cheatsheet/report.html q report.html Open in Browser •/ir Publish » 1 0 .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 along with the narration that a reader needs to understand your work. 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 reproduce your work and export the results as a finished report. Dynamic Documents • You can choose to export the finished report in a variety of formats, including html, pdf, MS Word, or RTF documents; html or pdf based slides, Notebooks, and more. ©j re port. Rmd \ > si r 2 title: "R Markdown" 3 author: "RStudio" 4 output: q 5 html_document: 6 toe: TRUE 0 j^T* Knit HTML - insert code chunk goto code chunk run"code \,setuP chunk(s) I""?*** publish Workflow ™. 1=- —-- "■'{r setup, include=FALSE} knitr::opts_chunk$set(echo = ifit R Markdown This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. '"■{r cars} summary(cars) run all previous chunks modify chunk options For more details on using R Markdown see . show outline Find in document R Markdown RStudio • R Markdown R Markdown synch publish button to accounts at rpubs.com, shinvapps.io RStudio Connect Reload document I This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. summary{cars} run current chunk ## speed dist ## Min. : 4 0 Hin. : 2.00 ## 1st Qu. 112 0 1st Qu. : 26.00 ## Median ■ 15 0 Median : 36.00 ## Mean 115 4 Mean : 42.98 ## 3rd Qu. :19 0 3rd Qu. : 56.00 ## Max. :25 0 Max. :120.00 For more details on using R Markdown see http://rmarkdown. rstudio.com. Open a new .Rmd file at File ► New File ► R Markdown. Use the wizard that opens to pre-populate the file with a template © Write document by editing template © Knit document to create report; use knit button c render() to knit 0 Preview Output in IDE window 0 Publish (optional) to web server @ Examine build log in R Markdown console © Use output file that is saved along side .Rmd 19:1 U R Markdown : con,,© R Markdown - / Desktop/ R-Markd own R Markdown i Ii b ra ry(rma rkdown) renderC'report.Rmd", output.file = "report.html") Files Plots Packages Help Viewer New Folder O Delete _ Rename More - [ j ^ Home Desktop R-Mar kdown-Cheats heel _© 9] report.Rmd report.html 398 B 581.3 KB Feb 26, 2016, 3:36 PM Feb 26, 2016, 3:36 PM render Use rmarkdown::render() to render/knit at cmd line. Important args: input file to render output_options output_file output format List of render output dir r - options fas in YAML) | r - pa rams list of params to use envir - environment encoding - of input to evaluate code file chunks in Embed code with knitr syntax INLINE CODE Insert with * r '. Results appear as text without code. Built with v rgetRversion()v Built with 3.2.3 CODE CHUNKS One or more lines surrounded with *{r} and * * *. Place chunk options within curly braces, after r. Insert with 1 {recho-TRUE} getRverSi0n,, getRversionf) GLOBAL OPTIONS Set with knitr::opts_chunk$set(), e.£ " " %{rinclude=FALSE} knitr::opts_chunk$set(echo - TRUE) IMPORTANT CHUNK OPTIONS cache - cache results 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-'##') @Stud 10 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) or stop render when errors occur (FALSE) (default -FALSE) eval- Run code in chunk (default - TRUE) Options not listed above: R.options, aniopts, 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.lp, fig.path, fig.pos, fig.process, fig.retina, fig.scap, fig.show, fig.showtext, fig.subcap, interval, out.extra, out.height, out.width, prompt, purl, ref.label, render, size, split, tidy.opts fig.align - 'left', 'right', 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 - Include chunk in doc 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) rmarkdown .rmd Structure . YAML Header Optional section of render (e.g. pandoc) options written as key:value pairs (YAML). At start of file Between lines of — Narration formatted with markdown, mixed with: Code Chunks Chunks of embedded code. Each chunk: Begins with *{r} ends with R Markdown will run the code and append the results to the doc. It will use the location of the .Rmd file as the working directory Parameters Parameterize your documents to reuse with different inputs (e.g., data, values, etc.) i- 1. Add parameters • Create and set parameters in the header as sub-values of params 2. Call parameters • Call parameter values in code as params$ 3. 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")) params: n: 100 d: IrSys.DateQ Today's date is v rparams$dv H *J blockquote #Headerl {#anchor} ## Header 2 {#css_id} ### Header 3 {.css_class} ####Header4 ##### Header 5 ###### Header 6 \textbf{Tex ignored in HTML} HTML ignored in pdfs [link](www.rstudio.com) Jump to [Header l](#anchor) image: [[Caption] (smallorb.png) * unordered list + sub-item 1 + sub-item 2 - sub-sub-item 1 * item 2 Continued (indent4spaces) 1. ordered list 2. item 2 i) sub-item 1 A. sub-sub-item 1 (@) A list whose numbering continues after (@) an interruption Term 1 : Definition 1 Right | Left | Default | Center | 12 | 12 | 12 | 12 | 123 | 1231 123 | 123 | 1 | 1| 1 | 1 | -slide bullet 1 -slide bullet 2 (>- to have bullets appear on click) horizontal rule/slide break: A footnote [Al] [Al]: Here is the footnote. @Stud Plain text End a line with two spaces to start a new paragraph. italics and bold verbatim code sub/su perse npt22 endash:-, emdash: — equation: A = n * r1 equation block: E = mc2 block quote Header! Header 2 Header 3 Header 4 Header 5 Header 6 HTML ignored in pdfs htt p://ww w. rstud io. com link Jump to Header 1 image: • unordered list ° 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 continues after 2. an interruption Term 1 Definition 1 Right Left Default Center 12 12 12 12 123 123 123 123 1 1 1 • slide bullet 1 • slide bullet 2 (>- to have bullets appear on click) horizontal rule/slide break: 1. Here is the footnote.*- IO Set render options with YAML 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 ^1 -fc. I knitr I , md rmarkdown Set a document's default output format in the YAML header: output value html_document pdf_document word_document odt_document rtf_document md_document github_document ioslides_presentation slidy_presentation beamer_presentation Customize output with sub-options (listed to the right): output: html_document # Body 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) output: html_document: code_folding: hide toc_float:TRUE # Body htmltabsets Use tablet ess class to place sub-headers into tabs # Tabset {.tabset .tabset-fade .tabset-pills} ## Tab 1 textl ## Tab 2 text 2 ### End tabset Tabset Tabl Tab 2 textl End tabset sub-option description E 1 1 1 1 f E citation_package The LaTeX package to process citations, natbib, biblatex or none X X X code_folding Let readers to toggle the display of R code, "none", "hide", or "show" X colortheme Beamer color theme to use X CSS CSS file to use to style document X X X dev Graphics device to use for figure output (e.g. "png") X X X X X X X duration Add a countdown timer fin minutes) to footer of slides X fig_caption Should figures be rendered with captions? X X X X X X X fig_height, fig_width Default figure height and width fin inches) for document X X X X X X X X X X highlight Syntax highlighting: "tango", "pygments", "kate","zenburn", "textmate" X X X X X includes File of content to place in document fin_header, before_body, after_body) X X X X X X X X incremental Should bullets appear one at a time fon presenter mouse clicks)? X X X keep_md Save a copy of .md file that contains knitr output X X X X X X keep_tex Save a copy of .tex file that contains knitr output X X latex_engine Engine to render latex, "pdflatex", "xelatex", or "lualatex" X X lib dir Directory of dependency files to use (Bootstrap, MathJax, etc.) X X X mathjax Set to local or a URL to use a local/URL version of MathJax to render equations X X X md_extensions Markdown extensions to add to default definition or R Markdown X X X X X X X X X X number_sections Add section numberingto headers X X pandoc_args Additional arguments to pass to Pandoc X X X X X X X X X X preserve_yaml Preserve YAML front matter in final document? X reference_docx docx file whose styles should be copied when producing docx output X self_contained Embed dependencies into the doc X X X slide_level The lowest heading level that defines individual slides X smaller Use the smaller font size in the presentation? X smart Convert straight quotes to curly, dashes to em-dashes,... to ellipses, etc. X X X template Pandoc template to use when rendering file quarterly_report.html). X X X X X theme Bootswatch or Beamer theme to use for page X X toe Add a table of contents at start of document X X X X X X X toc_depth The lowest level of headings to add to table of contents X X X X X X toc_float Float the table of contents to the left of the main content X Reusable Template Table Suggestions Create a 1. Create a new package with a inst/rmarkdown/templates directory 2. In the directory, Place a folder that contains: template.yaml (see below) skeleton.Rmd (contents of the template) anysupportingfiles 3. Install the package 4. Access template in wizard at Tile ► New rile ► R Markdown template.yaml name: My Template Citations Several functions format R data into tables Table with kable .... ■ eruptions waiting 3.60 79.00 1.80 54.00 3.33 74.00 2.28 62.00 Table with xtable Table with stargazer erupt ions waiting 3.333 2.283 and Bibliographies Create citations with .bib, .bibtex, .copac, .enl, .json, .medline, .mods, .ris, .wos, and .xml files 1. Set bibliography file and CSL 1.0 Style file (optional) in the YAML header 2. Use citation keys in text bibliography: refs.bib csl: style.csl data <-faithful[l:4,] 1 v {r results - 'asis'} nitr::kable(data, caption - "Table with kable") Smith cited [@smith04]. Smith cited withoutauthor [-@smith04]. @smith04 cited in line. 1 v {r results - "asis"} rint(xtable::xtable(data, caption - "Table with xtable"), type - "html", html.table.attributes - "border-0")) 1 v {r results - "asis"} stargazer::stargazer(data, type - "html", title - "Table with stargazer") 3. Render. Bibliography will be added to end of document Smith cited (Joe Smith 2004). Smith cited without author (2004). Joe Smith (2004) cited in line. RStudio® is a trademark of RStudio, Inc. • CCBYRStudio« info@rstudio.com • 844-448-1212 • rstudio.com • Learnmoreatrmarkdown.rstudio.com • rmarkdown 1.6 • Updated: 2016-02