You are on page 1of 2

R Markdown Cheat Sheet

.Rmd files Rmd


Reproducible Research Dynamic Documents
An R Markdown (.Rmd) file is a record of At the click of a button, or the type You can choose to export the
your research. It contains the code that a of a command, you can rerun the finished report as a html, pdf,
learn more at rmarkdown.rstudio.com
Rmd
scientist needs to reproduce your work code in an R Markdown file to MS Word, ODT, RTF, or
along with the narration that a reader reproduce your work and export markdown document; or as a
needs to understand your work. the results as a finished report. html or pdf based slide show.

RStudio
Workflow
Pro Features Interactive
DebugDocuments
Mode

1 Open a new .Rmd file at File New File R Markdown.


Use the wizard that opens to pre-populate the file with a 2 Write document
by editing template 3 Knit document to create report
Use knit button or render() to knit 4 Preview Output
in IDE window 5 Publish (optional)
to web or server
Turn your report into an interactive
Shiny document in 4 steps
template Synch publish button

1
Open in Save Spell Find and Publish Show to accounts at Add runtime: shiny to the
window Check replace outline rpubs.com, YAML header.
shinyapps.io
RStudio Connect
Reload document 2 Call Shiny input functions to embed
input objects.

3
Find in document
Call Shiny render functions to embed
File path to reactive output.
output document

4
.Rmd structure Set Insert Go to Run Render with rmarkdown::run or click
preview code code code Examine build log
YAML Header
Optional section of
location chunk chunk chunk(s) 6 in R Markdown console Run Document in RStudio IDE

render (e.g. pandoc)


options written as 7 Use output file that is
saved alongside .Rmd ---
output: html_document
key:value pairs (YAML).
runtime: shiny
At start of file ---
Between lines of - - - Modify Run all Run render()
chunk previous current
Text options chunks chunk Use rmarkdown::render() ```{r, echo = FALSE}
numericInput("n",
Narration formatted with to render/knit at cmd line.
"How many cars?", 5)
markdown, mixed with: Important args:
Code chunks input - file to render renderTable({
head(cars, input$n)
Chunks of embedded output_format })
code. Each chunk: output_options - List of ```
Begins with ```{r} render options (as in YAML)
ends with ``` output_file
R Markdown will run the output_dir Embed a complete app into your document with
code and append the shiny::shinyAppDir()
results to the doc. params - list of params to use
envir - environment to * Your report will rendered as a Shiny app, which means you
It will use the location of evaluate code chunks in must choose an html output format, like html_document,
the .Rmd file as the
working directory encoding - of input file and serve it with an active R Session.

Embed code
Debug
with
Mode
knitr syntax Debug
Parameters
Mode
Inline code Code chunks Global options Parameterize your documents to reuse with
Insert with `r <code>`. Results appear as text without code. One or more lines surrounded Set with knitr::opts_chunk$set(), e.g. dierent inputs (e.g., data sets, values, etc.)
```{r echo=TRUE}

1
with ```{r} and ```. Place
Built with getRversion()
chunk options within curly ```{r include=FALSE} Add parameters --- Indent 2
`r getRversion()` ``` knitr::opts_chunk$set(echo = TRUE)
braces, after r. Insert with Create and set params: spaces
```
Important chunk options parameters in the n: 100
header as sub-values d: !r Sys.Date()
cache - cache results for future knits dependson - chunk dependencies for fig.align - 'left', 'right', or 'center' (default message - display code messages in of params ---

2
(default = FALSE) caching (default = NULL) = 'default') document (default = TRUE)
Call parameters
cache.path - directory to save cached echo - Display code in output document fig.cap - figure caption as character results (default = 'markup') Todays date
results in (default = "cache/") (default = TRUE) string (default = NULL) 'asis' - passthrough results Call parameter
is `r params$d`
values in code as
child - file(s) to knit and then include engine - code language used in chunk fig.height, fig.width - Dimensions of 'hide' - do not display results params$<name>
(default = NULL) (default = 'R') plots in inches 'hold' - put all results below all code
collapse - collapse all output into single
block (default = FALSE)
error - Display error messages in doc
(TRUE) or stop render when errors occur
(FALSE) (default = FALSE)
highlight - highlight source code
(default = TRUE)
tidy - tidy code for display (default =
FALSE) 3 Set parameters
Set values wth Knit
with parameters or
comment - prefix for each line of results include - Include chunk in doc after warning - display code warnings in the params argument
eval - Run code in chunk (default = document (default = TRUE)
(default = '##') running (default = TRUE) of render():
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, render("doc.Rmd",
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 params = list(n = 1, d = as.Date("2015-01-01"))

RStudio is a trademark of RStudio, Inc. CC BY RStudio info@rstudio.com 844-448-1212 rstudio.com More cheat sheets at http://www.rstudio.com/resources/cheatsheets/ Learn more at rmarkdown.rstudio.com RStudio IDE 0.99.879 Updated: 02/16
Pandocs
DebugMarkdown
Mode Set render
Debug
options
Modewith YAML
Write with syntax on the left to create eect on right (after render) When you render, R Markdown

beamer
ioslides
gituhb
word
1. runs the R code, embeds results and text into .md file with knitr

slidy
html

md
odt
pdf
sub-option description

rtf
Plain text 2. then converts the .md file into the finished format with pandoc
End a line with two spaces
to start a new paragraph. citation_package The LaTeX package to process citations, natbib, biblatex or none X X X
*italics* and **bold** code_folding Let readers to toggle the display of R code, "none", "hide", or "show" X
`verbatim code`
colortheme Beamer color theme to use X
sub/superscript^2^~2~ Set a documents ---
~~strikethrough~~ default output format output: html_document css CSS file to use to style document X X X
in the YAML header: --- dev Graphics device to use for figure output (e.g. "png") X X X X X X X
escaped: \* \_ \\
endash: --, emdash: --- # Body duration Add a countdown timer (in minutes) to footer of slides X
equation: $A = \pi*r^{2}$ output value creates fig_caption Should figures be rendered with captions? X X X X X X X
equation block: html_document html fig_height, fig_width Default figure height and width (in inches) for document X X X X X X X X X X
$$E = mc^{2}$$ pdf_document pdf (requires Tex ) highlight Syntax highlighting: "tango", "pygments", "kate","zenburn", "textmate" X X X X X
> block quote word_document Microsoft Word (.docx) includes File of content to place in document (in_header, before_body, after_body) X X X X X X X X
# Header1 {#anchor} odt_document OpenDocument Text incremental Should bullets appear one at a time (on presenter mouse clicks)? X X X
rtf_document Rich Text Format keep_md Save a copy of .md file that contains knitr output X X X X X X
## Header 2 {#css_id}
md_document Markdown
### Header 3 {.css_class} keep_tex Save a copy of .tex file that contains knitr output X X
github_document Github compatible markdown
latex_engine Engine to render latex, "pdflatex", "xelatex", or "lualatex" X X
#### Header 4 ioslides_presentation ioslides HTML slides
lib_dir Directory of dependency files to use (Bootstrap, MathJax, etc.) X X X
##### Header 5 slidy_presentation slidy HTML slides
mathjax Set to local or a URL to use a local/URL version of MathJax to render X X X
###### Header 6 beamer_presentation Beamer pdf slides (requires Tex)
md_extensions Markdown extensions to add to default definition or R Markdown X X X X X X X X X X
<!--Text comment--> Indent 2 Indent 4
Customize output --- number_sections Add section numbering to headers X X
\textbf{Tex ignored in HTML} with sub-options output: spaces spaces
html_document: pandoc_args Additional arguments to pass to Pandoc X X X X X X X X X X
<em>HTML ignored in pdfs</em> (listed at right):
code_folding: hide preserve_yaml Preserve YAML front matter in final document? X
<http://www.rstudio.com> toc_float: TRUE reference_docx docx file whose styles should be copied when producing docx output X
[link](www.rstudio.com) html tabsets ---
self_contained Embed dependencies into the doc X X X
Jump to [Header 1](#anchor) Use .tabset css class # Body
to place sub-headers slide_level The lowest heading level that defines individual slides X
image:
into tabs smaller Use the smaller font size in the presentation? X
![Caption](smallorb.png)
smart Convert straight quotes to curly, dashes to em-dashes, to ellipses, etc. X X X
# Tabset {.tabset .tabset-fade .tabset-pills}
* unordered list template Pandoc template to use when rendering file X X X X X
+ sub-item 1 ## Tab 1
+ sub-item 2 text 1 theme Bootswatch or Beamer theme to use for page X X
- sub-sub-item 1 ## Tab 2 toc Add a table of contents at start of document X X X X X X X
text 2 toc_depth The lowest level of headings to add to table of contents X X X X X X
* item 2 ### End tabset toc_float Float the table of contents to the left of the main content X
Continued (indent 4 spaces)
Options not listed: extra_dependencies, fig_crop, fig_retina, font_adjustment, font_theme, footer, logo, html_preview,
1. ordered list reference_odt, transition, variant, widescreen
2. item 2
i) sub-item 1
A. sub-sub-item 1 Create aDebug
Reusable
Modetemplate Table
Debug
suggestions
Mode Citations
Debug
and Bibliographies
Mode

1
(@) A list whose numbering Create a new package with a Several functions format R data into tables Create citations with .bib, .bibtex, .copac, .enl, .json,
.medline, .mods, .ris, .wos, and .xml files
inst/rmarkdown/templates directory

1
continues after
Set bibliography file and CSL 1.0 Style
2
(@) an interruption In the directory, Place a folder that contains: file (optional) in the YAML header
Term 1 template.yaml (see below) ---
skeleton.Rmd (contents of the template) bibliography: refs.bib
: Definition 1
csl: style.csl
| Right | Left | Default | Center | any supporting files data <- faithful[1:4, ]

3
---

2
|------:|:-----|---------|:------:|
| 12 | 12 | 12 | 12 | ```{r results = 'asis'}
| 123 | 123 | 123 | 123 | Install the package Use citation keys in text
| 1 | 1 | 1 | 1 | knitr::kable(data, caption = "Table with kable")

4
Smith cited [@smith04].
Access ```
- slide bullet 1 Smith cited without author [-@smith04].
- slide bullet 2 template in @smith04 cited in line.
```{r results = "asis"}
wizard at File

3
print(xtable::xtable(data, caption = "Table with xtable"),
(>- to have bullets appear on click) New File type = "html", html.table.attributes = "border=0")) Render. Bibliography will be added to end
horizontal rule/slide break: R Markdown ``` of document
*** template.yaml ```{r results = "asis"} Learn more in
A footnote [^1] --- stargazer::stargazer(data, type = "html", the stargazer,
name: My Template xtable, and
[^1]: Here is the footnote. title = "Table with stargazer")
--- knitr packages.
```
RStudio is a trademark of RStudio, Inc. CC BY RStudio info@rstudio.com 844-448-1212 rstudio.com More cheat sheets at http://www.rstudio.com/resources/cheatsheets/ Learn more at rmarkdown.rstudio.com RStudio IDE 0.99.879 Updated: 02/16

You might also like