






















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
A comprehensive guide and reference for r markdown, a popular tool for creating dynamic and reproducible documents. It covers various options, chunk options, important chunk options, data manipulation functions, graph building templates, and general purpose scales. The document also introduces spark connection, spark dataframe, and sparklyr, an r interface for machine learning. It is a valuable resource for university students, high school students, and lifelong learners interested in data analysis, statistics, and machine learning.
Typology: Cheat Sheet
1 / 30
This page cannot be seen from the preview
Don't miss anything!
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at www.rstudio.com • RStudio IDE 0.99.832 • Updated: 2016-
Turn project into package, Enable roxygen documentation with Tools > Project Options > Build Tools
Roxygen guide at Help > Roxygen Quick Reference
File > New Project > New Directory > R Package
Share Project with Collaborators
Active shared collaborators
Select R Version
Start new R Session in current project
Close R Session in project
TH J
RStudio saves the call history, workspace, and working directory associated with a project. It reloads each when you re-open a project.
Name of current project
View() opens spreadsheet like view of data set
Sort by values
Filter rows by value or value range
Search for value
Viewer Pane displays HTML content, such as Shiny apps, RMarkdown reports, and interactive visualizations
Stop Shiny app
Publish to shinyapps.io, rpubs, RSConnect, …
Refresh
RStudio opens documentation in a dedicated Help pane
Home page of helpful links
Search within help file
Search for help file
GUI Package manager lists every installed package
Click to load package with library(). Unclick to detach package with detach()
Delete from library
Install Packages
Update Packages
Create reproducible package library for your project
RStudio opens plots in a dedicated Plots pane
Navigate recent plots
Open in window
Export plot
Delete plot
Delete all plots
Package version installed
Examine variables in executing environment
Open with debug(), browser(), or a breakpoint. RStudio will open the debugger mode when it encounters a breakpoint while executing code.
Open traceback to examine the functions that R called before the error occurred
Launch debugger mode from origin of error
Click next to line number to add/remove a breakpoint.
Select function in traceback to debug
Highlighted line shows where execution has paused
Run commands in environment where execution has paused
Step through code one line at a time
Step into and out of functions to run
Resume execution
Quit debug mode
Open Shiny, R Markdown, knitr, Sweave, LaTeX, .Rd files and more in Source Pane
Check spelling
Render output
Choose output format
Choose output location
Insert code chunk
Jump to previous chunk
Jump to next chunk
Run selected lines
Publish to server
Show file outline
Set knitr chunk options
Run this and all previous code chunks
Run this code chunk
Jump to chunk
RStudio recognizes that files named app.R , server.R , ui.R , and global.R belong to a shiny app
Run app
Choose location to view app
Publish to shinyapps.io or server
Manage publish accounts
Access markdown guide at Help > Markdown Quick Reference
Stage files:
Show file diff
Commit staged files
Push/Pull to remote
View History
current branch
Turn on at Tools > Project Options > Git/SVN
Open shell to type commands
A D M R ?
Search inside environment
Syntax highlighting based on your file's extension
Code diagnostics that appear in the margin. Hover over diagnostic symbols for details.
Tab completion to finish function names, file paths, arguments, and more.
Multi-language code snippets to quickly use common blocks of code.
Open in new window
Save Find and replace
Compile as notebook
Run selected code
Re-run previous code
Source with or without Echo
Show file outline
Jump to function in file Change file type
Navigate tabs
A File browser keyed to your working directory. Click on file or directory name to open.
Path to displayed directory
Upload file
Create folder
Delete file
Rename file
Change directory
Displays saved objects by type with short description
View function source code
View in data viewer
Load workspace
Save workspace
Import data with wizard
Delete all saved objects
Display objects as list or grid
Choose environment to display from list of parent environments
History of past commands to run/copy
Display .RPres slideshows File > New File > R Presentation
Working Directory
Maximize, minimize panes
Drag pane boundaries
TH J
Cursors of shared users
File > New Project
Press to see command history
Multiple cursors/column selection with Alt + mouse drag.
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at www.rstudio.com • RStudio IDE 0.99.832 • Updated: 2016-
Turn project into package, Enable roxygen documentation with Tools > Project Options > Build Tools
Roxygen guide at Help > Roxygen Quick Reference
File > New Project > New Directory > R Package
Share Project with Collaborators
Active shared collaborators
Select R Version
Start new R Session in current project
Close R Session in project
TH J
RStudio saves the call history, workspace, and working directory associated with a project. It reloads each when you re-open a project.
Name of current project
View() opens spreadsheet like view of data set
Sort by values
Filter rows by value or value range
Search for value
Viewer Pane displays HTML content, such as Shiny apps, RMarkdown reports, and interactive visualizations
Stop Shiny app
Publish to shinyapps.io, rpubs, RSConnect, …
Refresh
RStudio opens documentation in a dedicated Help pane
Home page of helpful links
Search within help file
Search for help file
GUI Package manager lists every installed package
Click to load package with library(). Unclick to detach package with detach()
Delete from library
Install Packages
Update Packages
Create reproducible package library for your project
RStudio opens plots in a dedicated Plots pane
Navigate recent plots
Open in window
Export plot
Delete plot
Delete all plots
Package version installed
Examine variables in executing environment
Open with debug(), browser(), or a breakpoint. RStudio will open the debugger mode when it encounters a breakpoint while executing code.
Open traceback to examine the functions that R called before the error occurred
Launch debugger mode from origin of error
Click next to line number to add/remove a breakpoint.
Select function in traceback to debug
Highlighted line shows where execution has paused
Run commands in environment where execution has paused
Step through code one line at a time
Step into and out of functions to run
Resume execution
Quit debug mode
Open Shiny, R Markdown, knitr, Sweave, LaTeX, .Rd files and more in Source Pane
Check spelling
Render output
Choose output format
Choose output location
Insert code chunk
Jump to previous chunk
Jump to next chunk
Run selected lines
Publish to server
Show file outline
Set knitr chunk options
Run this and all previous code chunks
Run this code chunk
Jump to chunk
RStudio recognizes that files named app.R , server.R , ui.R , and global.R belong to a shiny app
Run app
Choose location to view app
Publish to shinyapps.io or server
Manage publish accounts
Access markdown guide at Help > Markdown Quick Reference
Stage files:
Show file diff
Commit staged files
Push/Pull to remote
View History
current branch
Turn on at Tools > Project Options > Git/SVN
Open shell to type commands
A D M R ?
Search inside environment
Syntax highlighting based on your file's extension
Code diagnostics that appear in the margin. Hover over diagnostic symbols for details.
Tab completion to finish function names, file paths, arguments, and more.
Multi-language code snippets to quickly use common blocks of code.
Open in new window
Save Find and replace
Compile as notebook
Run selected code
Re-run previous code
Source with or without Echo
Show file outline
Jump to function in file Change file type
Navigate tabs
A File browser keyed to your working directory. Click on file or directory name to open.
Path to displayed directory
Upload file
Create folder
Delete file
Rename file
Change directory
Displays saved objects by type with short description
View function source code
View in data viewer
Load workspace
Save workspace
Import data with wizard
Delete all saved objects
Display objects as list or grid
Choose environment to display from list of parent environments
History of past commands to run/copy
Display .RPres slideshows File > New File > R Presentation
Working Directory
Maximize, minimize panes
Drag pane boundaries
TH J
Cursors of shared users
File > New Project
Press to see command history
Multiple cursors/column selection with Alt + mouse drag.
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at www.rstudio.com • RStudio IDE 0.99.832 • Updated: 2016-
Turn project into package, Enable roxygen documentation with Tools > Project Options > Build Tools
Roxygen guide at Help > Roxygen Quick Reference
File > New Project > New Directory > R Package
Share Project with Collaborators
Active shared collaborators
Select R Version
Start new R Session in current project Close R Session in project
TH J
RStudio saves the call history, workspace, and working directory associated with a project. It reloads each when you re-open a project.
Name of current project
View() opens spreadsheet like view of data set
Sort by values
Filter rows by value or value range
Search for value
Viewer Pane displays HTML content, such as Shiny apps, RMarkdown reports, and interactive visualizations
Stop Shiny app
Publish to shinyapps.io, rpubs, RSConnect, …
Refresh
RStudio opens documentation in a dedicated Help pane
Home page of helpful links
Search within help file
Search for help file
GUI Package manager lists every installed package
Click to load package with library(). Unclick to detach package with detach()
Delete from library
Install Packages
Update Packages
Create reproducible package library for your project
RStudio opens plots in a dedicated Plots pane
Navigate recent plots
Open in window
Export plot
Delete plot
Delete all plots
Package version installed
Examine variables in executing environment
Open with debug(), browser(), or a breakpoint. RStudio will open the debugger mode when it encounters a breakpoint while executing code.
Open traceback to examine the functions that R called before the error occurred
Launch debugger mode from origin of error
Click next to line number to add/remove a breakpoint.
Select function in traceback to debug
Highlighted line shows where execution has paused
Run commands in environment where execution has paused
Step through code one line at a time
Step into and out of functions to run
Resume execution
Quit debug mode
Open Shiny, R Markdown, knitr, Sweave, LaTeX, .Rd files and more in Source Pane
Check spelling
Render output
Choose output format
Choose output location
Insert code chunk
Jump to previous chunk
Jump to next chunk
Run selected lines
Publish to server
Show file outline
Set knitr chunk options
Run this and all previous code chunks
Run this code chunk
Jump to chunk
RStudio recognizes that files named app.R , server.R , ui.R , and global.R belong to a shiny app
Run app
Choose location to view app
Publish to shinyapps.io or server
Manage publish accounts
Access markdown guide at Help > Markdown Quick Reference
Stage files:
Show file diff
Commit staged files
Push/Pull to remote
View History
current branch
Turn on at Tools > Project Options > Git/SVN
Open shell to type commands
A D M R ?
Search inside environment
Syntax highlighting based on your file's extension
Code diagnostics that appear in the margin. Hover over diagnostic symbols for details.
Tab completion to finish function names, file paths, arguments, and more.
Multi-language code snippets to quickly use common blocks of code.
Open in new window
Save Find and replace
Compile as notebook
Run selected code
Re-run previous code
Source with or without Echo
Show file outline
Jump to function in file Change file type
Navigate tabs
A File browser keyed to your working directory. Click on file or directory name to open.
Path to displayed directory
Upload file
Create folder
Delete file
Rename file
Change directory
Displays saved objects by type with short description
View function source code
View in data viewer
Load workspace
Save workspace
Import data with wizard
Delete all saved objects
Display objects as list or grid
Choose environment to display from list of parent environments
History of past commands to run/copy
Display .RPres slideshows File > New File > R Presentation
Working Directory
Maximize, minimize panes
Drag pane boundaries
TH J
Cursors of shared users
File > New Project
Press to see command history
Multiple cursors/column selection with Alt + mouse drag.
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at www.rstudio.com • RStudio IDE 0.99.832 • Updated: 2016-
Turn project into package, Enable roxygen documentation with Tools > Project Options > Build Tools
Roxygen guide at Help > Roxygen Quick Reference
File > New Project > New Directory > R Package
Share Project with Collaborators
Active shared collaborators
Select R Version
Start new R Session in current project
Close R Session in project
TH J
RStudio saves the call history, workspace, and working directory associated with a project. It reloads each when you re-open a project.
Name of current project
View() opens spreadsheet like view of data set
Sort by values
Filter rows by value or value range
Search for value
Viewer Pane displays HTML content, such as Shiny apps, RMarkdown reports, and interactive visualizations
Stop Shiny app
Publish to shinyapps.io, rpubs, RSConnect, …
Refresh
RStudio opens documentation in a dedicated Help pane
Home page of helpful links
Search within help file
Search for help file
GUI Package manager lists every installed package
Click to load package with library(). Unclick to detach package with detach()
Delete from library
Install Packages
Update Packages
Create reproducible package library for your project
RStudio opens plots in a dedicated Plots pane
Navigate recent plots
Open in window
Export plot
Delete plot
Delete all plots
Package version installed
Examine variables in executing environment
Open with debug(), browser(), or a breakpoint. RStudio will open the debugger mode when it encounters a breakpoint while executing code.
Open traceback to examine the functions that R called before the error occurred
Launch debugger mode from origin of error
Click next to line number to add/remove a breakpoint.
Select function in traceback to debug
Highlighted line shows where execution has paused
Run commands in environment where execution has paused
Step through code one line at a time
Step into and out of functions to run
Resume execution
Quit debug mode
Open Shiny, R Markdown, knitr, Sweave, LaTeX, .Rd files and more in Source Pane
Check spelling
Render output
Choose output format
Choose output location
Insert code chunk
Jump to previous chunk
Jump to next chunk
Run selected lines
Publish to server
Show file outline
Set knitr chunk options
Run this and all previous code chunks
Run this code chunk
Jump to chunk
RStudio recognizes that files named app.R , server.R , ui.R , and global.R belong to a shiny app
Run app
Choose location to view app
Publish to shinyapps.io or server
Manage publish accounts
Access markdown guide at Help > Markdown Quick Reference
Stage files:
Show file diff
Commit staged files
Push/Pull to remote
View History
current branch
Turn on at Tools > Project Options > Git/SVN
Open shell to type commands
A D M R ?
Search inside environment
Syntax highlighting based on your file's extension
Code diagnostics that appear in the margin. Hover over diagnostic symbols for details.
Tab completion to finish function names, file paths, arguments, and more.
Multi-language code snippets to quickly use common blocks of code.
Open in new window
Save Find and replace
Compile as notebook
Run selected code
Re-run previous code
Source with or without Echo
Show file outline
Jump to function in file Change file type
Navigate tabs
A File browser keyed to your working directory. Click on file or directory name to open.
Path to displayed directory
Upload file
Create folder
Delete file
Rename file
Change directory
Displays saved objects by type with short description
View function source code
View in data viewer
Load workspace
Save workspace
Import data with wizard
Delete all saved objects
Display objects as list or grid
Choose environment to display from list of parent environments
History of past commands to run/copy
Display .RPres slideshows File > New File > R Presentation
Working Directory
Maximize, minimize panes
Drag pane boundaries
TH J
Cursors of shared users
File > New Project
Press to see command history
Multiple cursors/column selection with Alt + mouse drag.
library(shiny)
ui <- fluidPage( numericInput( inputId = "n" , "Sample size", value = 25), plotOutput( outputId = "hist" ) )
server <- function(input, output) { output$hist <- renderPlot ({ hist(rnorm( input$n )) }) }
shinyApp(ui = ui, server = server)
library(shiny) ui <- fluidPage( numericInput( inputId = "n" , "Sample size", value = 25), plotOutput( outputId = "hist" ) ) server <- function(input, output) { output$hist <- renderPlot ({ hist(rnorm( input$n )) }) }
shinyApp(ui = ui, server = server)
fluidPage( numericInput( inputId = "n" , "Sample size", value = 25), plotOutput( outputId = "hist" ) )
function(input, output) { output$hist <- renderPlot ({ hist(rnorm( input$n )) }) }
runApp(
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at shiny.rstudio.com • shiny 0.12.0 • Updated: 2016-
library(shiny)
ui <- fluidPage()
server <- function(input, output){}
shinyApp(ui = ui, server = server)
&
works with
wellPanel( dateInput("a", ""), submitButton() )
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at shiny.rstudio.com • shiny 0.12.0 • Updated: 2016-
ui <- fluidPage( textInput("a","","A") )
server <- function(input,output){ rv <- reactiveValues() rv$number <- 5 }
library(shiny) ui <- fluidPage( textInput("a","","A"), textOutput("b") )
server <- function(input,output){ output$b <- renderText({ isolate({input$a}) }) }
shinyApp(ui, server)
library(shiny) ui <- fluidPage( textInput("a","","A"), textOutput("b") )
server <- function(input,output){ output$b <- renderText({ input$a }) }
shinyApp(ui, server)
library(shiny) ui <- fluidPage( textInput("a","","A"), actionButton("go","Go") )
server <- function(input,output){ observeEvent(input$go,{ print(input$a) }) }
shinyApp(ui, server)
library(shiny) ui <- fluidPage( textInput("a","","A"), actionButton("go","Go"), textOutput("b") )
server <- function(input,output){ re <- eventReactive( input$go,{input$a}) output$b <- renderText({ re() }) }
shinyApp(ui, server)
ui <- fluidPage( textInput("a","","A"), textInput("z","","Z"), textOutput("b")) server <- function(input,output){ re <- reactive({ paste(input$a,input$z)}) output$b <- renderText({ re() }) } shinyApp(ui, server)
event.quoted, handler.env, handler.quoted, labe, suspended, priority, domain, autoDestroy, ignoreNULL )
Creates a reactive expression that
Call the expression with function syntax, e.g. re()
Add static HTML elements with tags , a list of functions that parallel common HTML tags, e.g. tags$a(). Unnamed arguments will be passed into the tag; named arguments will become tag attributes.
tags$a tags$abbr tags$address tags$area tags$article tags$aside tags$audio tags$b tags$base tags$bdi tags$bdo tags$blockquote tags$body tags$br tags$button tags$canvas tags$caption tags$cite tags$code tags$col tags$colgroup tags$command
tags$data tags$datalist tags$dd tags$del tags$details tags$dfn tags$div tags$dl tags$dt tags$em tags$embed tags$eventsource tags$fieldset tags$figcaption tags$figure tags$footer tags$form tags$h tags$h tags$h tags$h tags$h
tags$h tags$head tags$header tags$hgroup tags$hr tags$HTML tags$i tags$iframe tags$img tags$input tags$ins tags$kbd tags$keygen tags$label tags$legend tags$li tags$link tags$mark tags$map tags$menu tags$meta tags$meter
tags$nav tags$noscript tags$object tags$ol tags$optgroup tags$option tags$output tags$p tags$param tags$pre tags$progress tags$q tags$ruby tags$rp tags$rt tags$s tags$samp tags$script tags$section tags$select tags$small tags$source
tags$span tags$strong tags$style tags$sub tags$summary tags$sup tags$table tags$tbody tags$td tags$textarea tags$tfoot tags$th tags$thead tags$time tags$title tags$tr tags$track tags$u tags$ul tags$var tags$video tags$wbr
fluidPage( textInput("a","") )
Returns HTML
tags$head(tags$link(rel = "stylesheet", type = "text/css", href = "
tags$head(tags$script(src = "
column
column col
object 1
object 2
object 3
object 3
side panel
main
panel
object 1
object 2
object 3
ui <- fluidPage( fluidRow(column( width = 4 ), column( width = 2, offset = 3 )) , fluidRow(column( width = 12 )) )
ui <- fluidPage( flowLayout( # object 1,
) )
ui <- fluidPage( sidebarLayout( sidebarPanel(), mainPanel() ) )
ui <- fluidPage( splitLayout( # object 1,
) )
ui <- fluidPage( verticalLayout( # object 1,
) )
ui <- fluidPage( tabsetPanel( tabPanel("tab 1", "contents"), tabPanel("tab 2", "contents"), tabPanel("tab 3", "contents") ) )
ui <- fluidPage( navlistPanel( tabPanel("tab 1", "contents"), tabPanel("tab 2", "contents"), tabPanel("tab 3", "contents") ) )
ui <- navbarPage( title = "Page", tabPanel("tab 1", "contents"), tabPanel("tab 2", "contents"), tabPanel("tab 3", "contents") )
absolutePanel() conditionalPanel() fixedPanel() headerPanel() inputPanel() mainPanel()
navlistPanel() sidebarPanel() tabPanel() tabsetPanel() titlePanel() wellPanel()
ui <- fluidPage( h1("Header 1"), hr(), br(), p(strong("bold")), p(em("italic")), p(code("code")), a(href="", "link"), HTML(" Raw html
knitr:: **kable(** data, caption = "Table with kable” **)**
print(xtable:: **xtable(** data, caption = "Table with xtable” **)** , type = "html", html.table.attributes = "border=0"))
stargazer:: **stargazer(** data, type = "html", title = "Table with stargazer" **)**
Plain text End a line with two spaces to start a new paragraph. italics and bold verbatim code
sub/superscript^2^~2~ strikethrough escaped: * _ \ endash: --, emdash: --- equation: $A = \pi*r^{2}$ equation block:
$$E = mc^{2}$$
block quote
\textbf{Tex ignored in HTML} HTML ignored in pdfs
http://www.rstudio.com link Jump to Header 1 image:
Continued (indent 4 spaces)
(@) A list whose numbering
continues after
(@) an interruption
Term 1
: Definition 1
Right | Left | Default | Center |
---|---|---|---|
12 | 12 | 12 | 12 |
123 | 123 | 123 | 123 |
1 | 1 | 1 | 1 |
(>- to have bullets appear on click)
horizontal rule/slide break:
A footnote [1]
Write with syntax on the left to create effect on right (after render)
When you render, R Markdown
Set a document’s default output format in the YAML header:
output value creates
html_document html pdf_document pdf (requires Tex ) word_document Microsoft Word (.docx) odt_document OpenDocument Text rtf_document Rich Text Format md_document Markdown github_document Github compatible markdown ioslides_presentation ioslides HTML slides slidy_presentation slidy HTML slides beamer_presentation Beamer pdf slides (requires Tex)
Customize output with sub-options (listed to the right):
output: html_document: code_folding: hide toc_float: TRUE
Indent 4 spaces
Indent 2 spaces
html tabsets Use tablet css class to place sub-headers into tabs
text 1
text 2
Tabset
text 1 End tabset
Tab 1 Tab 2
name: My Template —
sub-option description
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 (in 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 (in 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 (in_header, before_body, after_body) X X X X X X X X incremental Should bullets appear one at a time (on 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 numbering to 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 toc 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
htmlpdfwordodtrtfmdgituhbioslidesslidybeamer
Several functions format R data into tables
Learn more in the stargazer, xtable , and knitr packages.
Create citations with .bib, .bibtex, .copac, .enl, .json, .medline, .mods, .ris, .wos, and .xml files
Smith cited [@smith04]. Smith cited without author [-@smith04]. @smith04 cited in line.
bibliography: refs.bib csl: style.csl
data <- faithful[1:4, ]
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at rmarkdown.rstudio.com • rmarkdown 1.6 • Updated: 2016-
rmarkdown
- haven - SPSS, Stata, and SAS files
x y z
A B C 1 2 3 4 5 NA
- col_guess() - the default **- col_character()
- col_factor( levels, ordered = FALSE **)
**- parse_guess()
**- parse_double()
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at tidyverse.org • readr 1.1.0 • tibble 1.2.12 • tidyr 0.6.0 • Updated: 2017-
w
wwwwww
w
www
www
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more with browseVignettes(package = c("dplyr", "tibble")) • dplyr 0.7.0 • tibble 1.2.0 • Updated: 2017-
- , e.g, -Species
wwwwww
wwwwww
wwwwww
wwwwww
wwwwww
wwwwww
wwww
wwwww
wwwwww
www
wwww
w
wwwwww
A B C A B C
wwww
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more with browseVignettes(package = c("dplyr", "tibble")) • dplyr 0.7.0 • tibble 1.2.0 • Updated: 2017-
C A B
A B 1 a t 2 b u 3 c v
1 a t 2 b u 3 c v
A B 1 a t 2 b u 3 c v
A B C 1 a t 2 b u 3 c v
A B C a t 1 b u 2 c v 3
A B D a t 3 b u 2 d w 1
A B C a t 1 b u 2 c v 3
A B D a t 3 b u 2 d w 1
A B C D a t 1 3 b u 2 2 c v 3 NA
A B C D a t 1 3 b u 2 2 d w N A 1
A B C D a t 1 3 b u 2 2
A B C D a t 1 3 b u 2 2 c v 3 NA d w NA 1
A B.x C B.y D a t 1 t 3 b u 2 u 2 c v 3 NA^ NA
A.x B.x C A.y B.y a t 1 d w b u 2 b u c v 3 a t
A1 B1 C A2 B a t 1 d w b u 2 b u c v 3 a t
A B C a t 1 b u 2 c v 3
A B C C v 3
DF A B C x a t 1 x b u 2 x c v 3 z c v 3 z d w 4
A B C c v 3
A B C a t 1 b u 2 c v 3 d w 4
A B C a t 1 b u 2
A B C a t 1 b u 2 c v 3
A B D a t 3 b u 2 d w 1
A B C c v 3
A B C a t 1 b u 2
A stat builds new variables to plot (e.g., count, prop).
data geom x = x · y = ..count..
coordinate system
plot
fl cty cyl x ..count..
stat
Visualize a stat by changing the default stat of a geom function, geom_bar(stat="count") or by using a stat function, stat_count(geom="bar") , which calls a default geom to make a layer (equivalent to a geom function). Use ..name.. syntax to map stat variables to aesthetics.
i + stat_density2d (aes(fill = ..level..), geom = "polygon" )
stat function geommappings
variable created by stat
geom to use
c + stat_bin( binwidth = 1, origin = 10 ) x, y | ..count.., ..ncount.., ..density.., ..ndensity.. c + stat_count( width = 1 ) x, y, | ..count.., ..prop.. c + stat_density( adjust = 1, kernel = “gaussian" ) x, y, | ..count.., ..density.., ..scaled..
e + stat_bin_2d( bins = 30, drop = T ) x, y, fill | ..count.., ..density.. e + stat_bin_hex( bins=30 ) x, y, fill | ..count.., ..density.. e + stat_density_2d( contour = TRUE, n = 100 ) x, y, color, size | ..level.. e + stat_ellipse(l evel = 0.95, segments = 51, type = "t" )
l + stat_contour( aes(z = z) ) x, y, z, order | ..level.. l + stat_summary_hex( aes(z = z), bins = 30, fun = max ) x, y, z, fill | ..value.. l + stat_summary_2d( aes(z = z), bins = 30, fun = mean ) x, y, z, fill | ..value..
f + stat_boxplot( coef = 1.5 ) x, y | ..lower.., ..middle.., ..upper.., ..width.. , ..ymin.., ..ymax..
f + stat_ydensity( kernel = "gaussian", scale = “area" ) x, y | ..density.., ..scaled.., ..count.., ..n.., ..violinwidth.., ..width..
e + stat_ecdf( n = 40 ) x, y | ..x.., ..y.. e + stat_quantile( quantiles = c(0.1, 0.9), formula = y ~ log(x), method = "rq" ) x, y | ..quantile.. e + stat_smooth( method = "lm", formula = y ~ x, se=T, level=0.95 ) x, y | ..se.., ..x.., ..y.., ..ymin.., ..ymax..
ggplot() + stat_function( aes(x = -3:3), n = 99, fun = dnorm, args = list(sd=0.5) ) x | ..x.., ..y..
e + stat_identity( na.rm = TRUE ) ggplot() + stat_qq( aes(sample=1:100), dist = qt, dparam=list(df=5) ) sample, x, y | ..sample.., ..theoretical..
e + stat_sum() x, y, size | ..n.., ..prop.. e + stat_summary(f un.data = "mean_cl_boot" ) h + stat_summary_bin( fun.y = "mean", geom = "bar" ) e + stat_unique()
Scales map data values to the visual values of an aesthetic. To change a mapping, add a new scale.
(n <- d + geom_bar(aes(fill = fl)))
n + scale_fill_manual( values = c("skyblue", "royalblue", "blue", “navy"), limits = c("d", "e", "p", "r"), breaks =c("d", "e", "p", “r"), name = "fuel", labels = c("D", "E", "P", "R") )
scale_
aesthetic to adjust
prepackaged scale to use
scale-specific arguments
title to use in legend/axis
labels to use in legend/axis
breaks to use in legend/axis
range of values to include in mapping
Use with most aesthetics scale__continuous()* - map cont’ values to visual ones scale__discrete()* - map discrete values to visual ones scale__identity()* - use data values as visual ones scale__manual(* values = c() ) - map discrete values to manually chosen visual ones scale__date(* date_labels = "%m/%d"), date_breaks = " weeks" ) - treat data values as dates. scale__datetime()* - treat data x values as date times. Use same arguments as scale_x_date(). See ?strptime for label formats.
Use with x or y aesthetics (x shown here) scale_x_log10() - Plot x on log10 scale scale_x_reverse() - Reverse direction of x axis scale_x_sqrt() - Plot x on square root scale
n <- d + geom_bar( aes(fill = fl) )
n + scale_fill_brewer( palette = "Blues" ) For palette choices: RColorBrewer::display.brewer.all() n + scale_fill_grey( start = 0.2, end = 0.8, na.value = "red" )
o <- c + geom_dotplot(aes(fill = ..x..))
o + scale_fill_distiller( palette = "Blues" )
o + scale_fill_gradient( low="red", high="yellow" )
o + scale_fill_gradient2( low="red", high=“blue", mid = "white", midpoint = 25)
o + scale_fill_gradientn( colo u rs=topo.colors(6) ) Also: rainbow(), heat.colors(), terrain.colors(), cm.colors(), RColorBrewer::brewer.pal()
p <- e + geom_point(aes(shape = fl, size = cyl)) p + scale_shape() + scale_size() p + scale_shape_manual( values = c(3:7) )
p + scale_radius( range = c(1,6) ) p + scale_size_area( max_size = 6 )
r <- d + geom_bar() r + coord_cartesian( xlim = c(0, 5) ) xlim, ylim The default cartesian coordinate system r + coord_fixed( ratio = 1/2 ) ratio, xlim, ylim Cartesian coordinates with fixed aspect ratio between x and y units r + coord_flip() xlim, ylim Flipped Cartesian coordinates r + coord_polar( theta = "x", direction=1 ) theta, start, direction Polar coordinates r + coord_trans( ytrans = “sqrt" ) xtrans, ytrans, limx, limy Transformed cartesian coordinates. Set xtrans and ytrans to the name of a window function.
π + coord_quickmap() π + coord_map( projection = "ortho", orientation=c(41, -74, 0) ) projection, orienztation, xlim, ylim Map projections from the mapproj package (mercator (default), azequalarea, lagrange, etc.)
Position adjustments determine how to arrange geoms that would otherwise occupy the same space.
s <- ggplot(mpg, aes(fl, fill = drv)) s + geom_bar(position = "dodge") Arrange elements side by side s + geom_bar(position = "fill") Stack elements on top of one another, normalize height e + geom_point(position = "jitter") Add random noise to X and Y position of each element to avoid overplotting e + geom_label(position = "nudge") Nudge labels away from points
s + geom_bar(position = "stack") Stack elements on top of one another
Each position adjustment can be recast as a function with manual width and height arguments s + geom_bar(position = position_dodge(width = 1))
A B
r + theme_bw() White background with grid lines r + theme_gray() Grey background (default theme) r + theme_dark() dark for contrast
r + theme_classic()
r + theme_light() r + theme_linedraw() r + theme_minimal() Minimal themes r + theme_void() Empty theme
Facets divide a plot into subplots based on the values of one or more discrete variables.
t <- ggplot(mpg, aes(cty, hwy)) + geom_point()
t + facet_grid(. ~ fl) facet into columns based on fl t + facet_grid(year ~ .) facet into rows based on year t + facet_grid(year ~ fl) facet into both rows and columns t + facet_wrap(~ fl) wrap facets into a rectangular layout
Set scales to let axis limits vary across facets
t + facet_grid(drv ~ fl, scales = "free") x and y axis limits adjust to individual facets "free_x" - x axis limits adjust "free_y" - y axis limits adjust
Set labeller to adjust facet labels
t + facet_grid(. ~ fl, labeller = label_both)
t + facet_grid(fl ~ ., labeller = label_bquote( alpha ^ .(fl )))
t + facet_grid(. ~ fl, labeller = label_parsed)
fl: c fl: d fl: e fl: p fl: r
c d e p r
↵c^ ↵d^ ↵e^ ↵p^ ↵r
t + labs( x = "New x axis label", y = "New y axis label", title ="Add a title above the plot", subtitle = "Add a subtitle below title", caption = "Add a caption below plot",
Use scale functions to update legend labels
geom to place manual values for geom’s aesthetics
n + theme( legend.position = "bottom" ) Place legend at "bottom", "top", "left", or "right" n + guides( fill = "none" ) Set legend type for each aesthetic: colorbar, legend, or none (no legend) n + scale_fill_discrete( name = "Title", labels = c("A", "B", "C", "D", "E") ) Set legend title and labels with a scale function.
Without clipping (preferred) t + coord_cartesian( xlim = c(0, 100), ylim = c(10, 20) ) With clipping (removes unseen data points)
t + xlim( 0, 100 ) + ylim( 10, 20 ) t + scale_x_continuous( limits = c(0, 100) ) + scale_y_continuous( limits = c(0, 100) )
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at http://ggplot2.tidyverse.org • ggplot2 2.1.0 • Updated: 2016-
60
long
lat
p q r
a b c
a b c d
a b c d a b c d
a b c d
a b c d
a b c d
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at purrr.tidyverse.org • purrr 0.2.3 • Updated: 2017-
a b c d
b
a b c
a c
a b
a b c d
a^ NULL b c NULL
b
a b c
x y a b c
x y
a b c
a b c
x y z (^2)
a b c
FALSE
a b c
TRUE
a b c
TRUE
a b c
c
a b c
a b
c
d
c
d
fun
fun
fun
fun
fun fun
a b c
b
a string {xx} {yy}
A STRING
A STRING
a string
a string
A String
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at stringr.tidyverse.org • Diagrams from @LVaudor • stringr 1.2.0 • Updated: 2017-
TRUE TRUE FALSE TRUE
1 2 4 0 3 1 2
start end 2 4 4 7 NA NA 3 4
4 6 2 3
4 1 3 2
NA NA
NA
regexp matches example
string (type this)
regexp (to mean this)
matches (which matches this)
example (the result is the same as ref("abba"))
regexp matches example
regexp matches example
Special Character Represents
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at stringr.tidyverse.org • Diagrams from @LVaudor • stringr 1.2.0 • Updated: 2017-
regexp matches example
(^1) Many base R functions require classes to be wrapped in a second set of [ ] , e.g. [[:digit:]]
string (type this)
regexp (to mean this)
matches (which matches this)
example
1 1 1 1 1 1 1 1 1
regexp matches example
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at lubridate.tidyverse.org • lubridate 1.6.0 • Updated: 2017-
Number of days etc.
Number of months
Exact length in seconds
Equivalent in common units
Start Date
End Date
nor <- ymd_hms("2018-01-01 01:30:00",tz="US/Eastern")
gap <- ymd_hms("2018-03-11 01:30:00",tz="US/Eastern")
lap <- ymd_hms("2018-11-04 00:30:00",tz="US/Eastern")
leap <- ymd("2019-03-01")
12:00 1:00 2:00 3:
2019 2020 2021
1:00 2:00 3:00 4:
1:00 2:00 3:00 4:
12:00 1:00 2:00 3:
2019 2020 2021
1:00 2:00 3:00 4:
1:00 2:00 3:00 4:
12:00 1:00 2:00 3:
1:00 2:00 3:00 4:
1:00 2:00 3:00 4:
2019 2020 2021
12:00 1:00 2:00 3:
1:00 2:00 3:00 4:
1:00 2:00 3:00 4:
2019 2020 2021
Package: mypackage Title: Title of Package Version: 0.1. Authors@R: person("Hadley", "Wickham", email = "hadley@me.com", role = c("aut", "cre")) Description: What the package does (one paragraph) Depends: R (>= 3.1.0) License: GPL- LazyData: true Imports: dplyr (>= 0.4.0), ggvis (>= 0.2) Suggests: knitr (>= 0.1.0)
Suggest packages that are not very essential to yours. Users can install them manually, or not, as they like.
�
�
�
context("Arithmetic")
test_that("Math works", { expect_equal(1 + 1, 2) expect_equal(1 + 2, 3) expect_equal(1 + 3, 4) })
RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at http://r-pkgs.had.co.nz/ • devtools 1.5.1 • Updated: 2015-
- source - a directory with sub-directories (as above) - bundle - a single compressed file (.tar.gz) - binary - a single compressed file optimized for a specific OS
Internet On disk library memory
�
�
MIT license applies to your code if re-shared.
�
�
- Use consistent style with r-pkgs.had.co.nz/r.html#style - Click on a function and press F2 to open its definition - Search for a function with Ctrl +.
Import packages that your package must have to work. R will install them when it installs your package.
GPL-2 license applies to your code, and all code anyone bundles with it, if re-shared.
No strings attached.
Expect statement Tests
expect_equal() is equal within small numerical tolerance? expect_identical() is exactly equal? expect_match() matches specified string or regular expect_output() expression?prints specified output? expect_message() displays specified message? expect_warning() displays specified warning?
expect_error() throws specified error? expect_is() output inherits from certain class? expect_false() returns FALSE? expect_true() returns TRUE?
�
Here is the footnote. ↩