2.7 The R Studio Cheatsheet. RStudio conveniently points to printable “cheatsheets” that you find useful. Go to Help cheatsheets, and there you will find the RStudio IDE Cheat Sheet. Clicking on the link will download the cheatsheet pdf to your system, where you can print or save it for future reference. No matter what you do with R, the RStudio IDE can help you do it faster. This cheat sheet will guide you through the most useful features of the IDE, as well as the long list of keyboard shortcuts built into the RStudio IDE. Updated January 2016. Rstudio ide-cheatsheet 1. Documents and Apps Project System Write Code R Support RStudio Pro Features Debug Mode Version Control with Git or SVN Package Writing Project System Write Code R Support RStudio Pro Features Debug Mode Version Control with Git or SVN Package Writing Turn project into package, Enable roxygen documentation with Tools Project Options Build Tools Roxygen guide at.
Key Concepts
This chapter introduces RStudio, a Graphical User Interface (GUI) that makes it easier to use powerful features in R and manage large projects.
New vocabulary:
- Integrated Development Environment (IDE)
- RStudio Panes:
- Console
- Source
- Plots
- Viewer
- Environment
- History
- Workspace & Global Environment
What is RStudio?
Recall that R is both a language and an environment. RStudio is an Integrated Development Environment, or IDE, which is an enhanced, feature-rich programming environment with an easy-to-use graphical user interface, or GUI. While the base R environment is mostly text, RStudio has intuitive icons (hence, “graphical”) for point-and-click, automated operations.
RStudio’s layout is comprised of a menu, console, and a series of panes, or windows in the RStudio interface. Most panes are feature-rich and all panes serve a key purpose, but we’ll only focus on the most critical panes for getting started in RStudio.
The RStudio environment with four open panes: The Source, Console, Environment, and Viewer panes.
Downloading & Installing RStudio
RStudio requires R 3.0.1+. If you don’t already have R, download it here.
RStudio is free, open source, and easy to install. Select the Desktop edition on their download page:
A Tour of RStudio
RStudio is comprised of a main menu and a series of panes, each with their own purpose and features. We focus on the following:
- Console Pane
- Source Pane
- Plots Pane
- Viewer Pane
- Environment Pane
- History Pane
The Console Pane
The console pane is where R expressions are evaluated. In other words, this is where your code is executed. Recall that working in-console is also known as working interactively and, typically, working in-console is more often for “quick and dirty” tasks, like printing contents of your working directory.
The Console Pane
The console is where code is executed and is typically used for “quick and dirty” tasks.
The console panel lists your current working directory. Notably, even when using point-and-click mechanics to, e.g. import data or change directories, the code for such tasks will still execute in the console. Such click-to-code operations are called macros.
Pro Tip: When writing a script, especially when writing out new directory paths, it’s sometimes quicker to use use a click-to-code operation and simply copy and paste the macro code from the console to your script.
The Source Pane
The source pane contains any opened scripts. In starting a new R session, this pane isn’t visible until you’ve opened a new or preexisting script. Multiple scripts may be opened at one time and are navigable using tabs along the top of the source pane.
The Source Pane
The source pane contains opened scripts. It won’t appear until you’ve opened at least one.
Depending on the type of script, e.g. plain text scripts (.R
), publications (.Rmd
), presentations (.Rpres
), and apps, each script provides different options in the pane’s toolbar. Common options include:
- Show in New Window: Open the script in a separate window; valuable for two or more monitors
- Save Current Document: Update an existing script or title and save a new script
- Find/Replace: Both conventional and advanced options to find and replace code
- Run: Run the line of code where the cursor is, or multiple lines if highlighted
- Show Document Outline: View (and jump to) script’s table of contents
Plots, Viewer, & Help Panes
The Plots, Viewer, and Help panes are used to viewing data visualizations, HTML output, and helpful documentation.
The Plots Pane
The Plots pane allows users to view, export, and publish non-interactive data visualizations. R uses the built-in graphics
package by default, but a variety of packages exist such as lattice
and ggplot2
. While the output displayed is not interactive, it is responsive, i.e it will re-render its scales appropriately if you change the height or width of a plot. Notably, the “Zoom” option opens visualizations in a new window, while the “Export” option allows you to save the image with user-defined dimensions and in a variety of formats.
The Viewer Pane
The Viewer pane renders interactive graphics in HTML with the same options as the Plots pane. Brevity aside, it’s awesome.
The Plots & Viewer Panes
The Plots and Viewer panes visualize non-interactive and interactive graphics, respectively.
The Help Pane
The Help pane is one of the most valuable panes for any R user. By calling function help()
with a dataset, package, or bare function name (i.e. a function name without ()
), its documentation, if available, appears here.
Note: Unless you’re using external data or custom functions, there’s almost always documentation. Whether it’s the unit of measurement for a variable in a dataset or the limits you can specify for a function argument, this little nook in RStudio is invaluable to new and advanced users, alike.
Pro Tip: Instead of the help()
function, you can use the ?
function before an object name, e.g. ?install.packages
.
The Help Pane
The invaluable Help pane displays documentation for packages, functions, and datasets.
The Environment and History Panes
The Environment and History panes display the objects in your environment and the history of your in-console commands.
The Environment Pane
Again, R is both a language and an environment. The Environment pane displays objects that are stored within your session’s workspace, or global environment, which must be recreated or reloaded with each new session. Note the following options:
- Environment: Opens a dropdown menu to select different environments, e.g. package environments
- Load Workspace: Opens a file explorer to load previously saved workspaces and their objects
- Import Datasets: Opens a dropdown menu to read in datasets that you can store in objects
- Clear Objects from Workspace: Removes all objects stored in the global environment
The Environment Pane
The environment pane displays any objects you’ve imported, loaded, or stored in your global environment.
The History Pane
The History pane documents every command you’ve executed in your session. When you select a line, you can paste it directly into the console pane with “To Console” or directly into the source pane with “To Source”.
The History Pane
The history pane records every command you’ve run in your session.
Customizing Your Pane Layout
In RStudio, you can customize both where panes are displayed as well as which panes to show by default.
Layouts for Beginners: Taking Great Panes
Panes cannot be removed entirely from the RStudio interface, you but can shuffle them by order of importance. Click the “Tools” dropdown in themenu, “Global Options…”, and “Pane Layout”. We recommend focusing on those discussed in this chapter.
Customizing Pane Layout
You can customize which panes appear, and where, in Global Options’ Pane Layout.
Less Important Panes, or Panes in the Rear
There are a couple of panes worth mentioning for new users. However, they are seldom used by advanced users:
- Files: Set working directories and create, copy, rename, and delete folders
- Packages: Install, load, update, unload, and uninstall added (“User Library”) and built-in (“System Library”) packages
Pro Tip: You probably won’t use these panes often. One of the benefits of scripted languages is that they can be reproduced by other users. As a rule, since much of your work will require loading packages, you should include the library()
function with script-dependent packages at the start of every work. The same applies to working directories with the setwd()
function.
Expanding to Fullscreen: Focus on the Pane
If you want to expand a pane, or “zoom”, to fullscreen mode, select “View” in the RStudio menu and “Panes”.
Toggling Fullscreen Panes
You can expand any pane to fullscreen mode in the “View” dropdown of the RStudio menu.
The RStudio Menu: File, Session, & Help
The RStudio menu allows you to do virtually everythign we’ve seen in each pane and more. The following tours a few key menu sections we’ve not yet seen, including how to open new scripts, handle sessions, and access R-related cheat sheets.
The File Submenu: Saving & Loading
The File submenu is the start of every scripted data product in RStudio. Just select “New File” and a litany of possible data products, about which we’ll learn more over time, are available to open. Remaining options relate to the saving and loading of scripts, projects, and datasets.
The File Submenu
“File” handles all new, saving, and loading operations.
The Session Submenu: Sessions, Directories, & Restarting R
The Session submenu is a critical part of any R session. While you can always recreate a session by recreating objects, you can save computing time by loading saved session file. This submenu also allows you to set your working directory.
Note: There are times when you just have to restart R - maybe you started an infinite recursion loop or maybe you attempted to read in the data from a month’s worth of Harrier Jet landings to local memory - if so, the “Restart R” option is here for you.
The Session Submenu
Save and load sessions, restart R, or handle directories in the session submenu.
The Help Submenu: Cheat Sheets
The help menu has one main draw (for now): cheat sheets. Selecting a cheat sheet will automatically download a cheat sheet on an R-related topic of your choosing. Typically, cheat sheets summarize RStudio related packages and data products, but there is one for base R. For example, you can find the RStudio IDE cheat sheet here.
The Help Submenu
Grab cheat sheets on the fly from the Help submenu.
Global Options: Aesthetic & Functional Preferences
Global options are accessed in the “Tools” submenu and allow users to modify their RStudio interface in myriad ways, both aesthetically and functionally. We recommend new users experiment with these options and visit a few notable modifications.
Accessing Global Options
Code: Autoformatting & Behavior
The “Code” section affects the way R automatically formats your code and how you choose to write and run it. It has sensible defaults, many of which you may not be prepared to appreciate quite yet. For now, consider the following:
- Indentating: In the “Editing” tab, consider a “tab width” that works best for you. When indenting, would you prefer two characters (i.e. spaces), or four? The former allows more compact code. The latter allows for more intepretable code.
- Guide Margin: In the “Display” tab, consider applying a “margin column” of 80 or 100 characters (i.e. spaces). This creates a subtle guide in your scripts that helps keep code concise and readable. Even basic code within basic code can create, what RStudio’s Chief Scientist Hadley Wickham refers to as, “Dagwood sandwich” code.
Appearance: Express Yourself Intepretably
The Appearance section allow you to customize the size, font, and color of your text as well as the “theme” colors of your RStudio interface. Here, “theme” is both functional and aesthetic. For example, darker themes are more conducive to night owls. For all themes, certain syntax uses different colors to make your code more interpretable - keep this in mind for each theme!
Notable Global Options: Code & Appearance
Global options allow you to set preferences that can significantly impact your experience with RStudio.
Further Resources
The following resources are helpful in learning more about RStudio and coding conventions:
I) Full Introductions to RStudio
- “What are R and RStudio?” (Ismay & Kim, 2019)
- “Intro to R: Nuts & Bolts” (Crawford, 2018)
II) About RStudio
- RStudio Homepage (RStudio, 2019)
- RStudio About Page (RStudio, 2019)
- RStudio Product Page (RStudio, 2019)
III) Conventions
- “The State of Naming Conventions in R” (Baath, 2012)
Foreword
- Output options: the ‘tango’ syntax and the ‘readable’ theme.
- Snippets and results.
Help:Alt+Shift+K or Tools/Keyboard Shortcuts Help.
Orientation¶
Commands
- Ctrl+Up; command history.
- Tab; completion for all.
- Ctrl+L; clear the console.
- Tools/Global Options… set up RStudio.
view(dataframe)
; open a spreadsheet, show in new window, sort the
rows, search, filter the rows.
IDE panes
- Environment pane; load, save, remove objects, read a dataset,
import dataset. - History pane; idem, clear all or one item at the time, copy the
command in the console pane, reload a command with Shift+Enter and
run it. - File pane; working directories, files, add a new folder, rename
getwd()
; get working directory.setwd()
; set working directory.- Plot pane; save (extension, size, resolution).
- Package pane; update.
- Help pane; pages.
- Viewer pane; more than plots!
Programming¶
Scripting
- Ctrl+Shift+M;
%>%
. - Alt+-;
<-
. - Ctrl+Shift+C; add/delete a
#
for commenting.
Code
Ctrl+Alt+I; new chunk.
Convert into a function.
- Type code,
- Highlight it,
- Code/Extract Function to create a function:
This:
Becomes:
- Ctrl+Alt+click; multiple cursors for typing!
- Switch between Default, Vim and Emacs modes with
Tools/Global Options/Code/Keybindings. - Shift+Alt+G; go to line.
- Ctrl+F: find/replace in the current document.
- Alt+O, Alt+Shift+O; fold/unfold the code.
- Ctrl+P; jump between symbols like (), {}, [].
- Ctrl+Shift+Enter; run and source the code.
- Ctrl+Enter; run and source the code.
- Ctrl+Shift+F10; restart, refresh the R session.
Error handling
RStudio traces back the error origin.
Toggle the show/hide traceback in the console when there is an error or
rerun with the bug, watch the right pane for traceback.
Investigate, highlight the next line of code, click in the traceback
window, click the dropdown menu in the Global Environment (upper-right).
Stop, continue in the debugger mode, press C, press Q.
Add/remove breakpoints, where the line numbers are.
debugonce
; automatically call the debugger when the function is
called, but only once.debug
,undebug
; automatically call the debugger when the
function is called.
Add options(error=browser)
or options(error=NULL)
at the beginning
of the script; R automatically open the debugger mode.
- N; next line.
- step-into icon.
- Shift+F4; step into.
- Shift+F6; execute the remainder of the bug.
Project¶
- Create a project with a folder and all the files (Global
Environment, History, etc.): New Directory, Existing Directory,
Version Control… Empty Project, R Package (project), Shiny
Web Application. - Create a Git repository with the new project
Commands
- Ctrl+Shift+F; find in files.
- Ctrl+F9, F10; go backwards/forwards.
Packrat
Packrat is a dependency management system for R. Use one version of a
package for one project, another version of a package for another
project. Associate a project with its own set of packages.
- Packrat.
- Activate Packrat when creating a project or
Tools/Project Options/Packrat. - The library is virtually separate from R library.
- Perfect for collaborating with GitHub
Packages¶
Introduction to R packages
Anything that can be automated, should be automated. Do as little as
possible by hand. Do as much as possible with functions.
Process:
- Writing R functions.
- Documenting functions.
- Writing tests.
- Checking compatibility.
- Building the package for sharing and using.
See the book: R Packages.
Create a new R package
Create a new directory with new files, folders, and meta-information.
To update or not to update
RStudio generates the NAMESPACE content for you automatically.
See the book: R Packages.
Import & load source files
Move existing functions from an existing project into the new package.
The function are moves to a new folder in the project.
Test created functions all in once with the Load All command in the
Build Tab.
Simulations:
- Ctrl+Shift+L
- Ctrl+Shift+F10; restart a R session.
Packages documentation
Create a help page (.Rd file). Written in HTML.
Use the roxigen
package to document.
Tools/Project Optons/Build Tools/Generate documentation. Generate the
doc, add comments.
First, create a doc skeleton above the function:
- Ctrl+Alt+Shift+R
Fill in the blanks.
Package documentation (2)
Title of the help page. Text on how to use.
The 4 tags (@
) help organizing the doc: @export
(tells R that this
function should be made available to people who load your package. ),@params
, @return
, and @examples
. There are many more advanced
tags.
Highlight a section and test it, run it.
Package documentation (3)
Build Tab/build the package.
- Ctrl+Shift+D
R Studio Commands Cheat Sheet
Compile all. Load all. Open the help page with ?function
.
Learn the roxigen
workflow to ease the work.
Test your package
With the testthat
(and devtools
) package.
Install both packages. Run devtools::use_testthat()
and a now
directory with subdir appears in the package. This is where we save
tests.
Test your package (2)
Ready. Write tests. Open a new R script and save it to the tests
directory. Create a context
function. Add test_that
functions with
arguments.
Test your package (3)
Run the tests.
- Ctrl+Shift+T
Get a summary (pass or not pass). Test and retest the package.
See the book: R Packages.
Time to test your package
Run the test with Build Tab/Test package.
Check your package
Upload the package to GitHub. Recreate the package structure in the
repo. Download and install the package with install_github()
from thedevtools
package. Test the package on GitHub to complete the tests.
Type RCMDcheck
in the terminal. Or Build Tab/Check icon.
- Ctrl+Shift+E
Build your package
A package is a tarball or package bundle.
Build Tab/Build & Reload. Install and load the package.
- Ctrl+Shift+B
Build and reload will overwrite the existing package. Rundevtools::dev_mode()
creates a separate library for development.
Running the command again cancels it.
Two formats: source package or binary package (more compresses and
optimized).
See the book: R Packages.
Wrap-up
Get the cheat sheet
Version Control¶
Introduction to Git
Use Git to work in team. Even on R scripts, reports and packages.
Install Git.
In RStudio, Tools/Global Options/Git/SVN + Tools/Project Options/Select
VCS, restart RStudio. RStudio has now a Git pane and a Git icon.
Stage & commit
The Git Tab is a directory. The real life (local) version of the
project. The official version of the project as recorded with Git.
R Cheat Sheets
The two versions are different. View the differences. When you commit,
you add thing from the real to the official version.
Green highlighting indicates something you’ve added to the official
version, while red highlighting indicates lines you have removed.
.gitignore
Inside the project, ther is a .gignore file. Add file that are excluded
from the offcial version. The file can be accessed from the Git pane.
Git icons
Add, (cancel), commit, (cancel). The icons will changed.
Commit history
History viewer: each commitment. HEAD commit and parent commit. Master
branch or another.
Undo commited changes: checkout
Checkout command. Go back to a previous commit. The commit stays in the
history (not deleted).
Run it in the shell: Tools/shell.
gitcheckoutsha#nameofthefile
and Git will reverse the commit. The
file is in the stage area as before the commit.
Undo uncommited changes
The file is in the stage area, ready to commit. Cancel the addition.
In the Change window, click on the Revert button.
Or, click on Discard chunk.
Or, Ctrl+Z to undo.
Then, Save the file.
Introduction to GitHub
Centralize, host, track issues, track metrics.
Install a R package From GitHub with install_github
from the thedevtools
packages.
Pull & Push
Local and GitHub
Wrap-up
Go to help.github.com
Go to stackoverflow.com
Reporting¶
Tools for reporting
R Markdown and Shiny (over the web).
Introduction to R Markdown
Text and code.
Web link: <http://www>
R Markdown in RStudio
Report (HTML, PDF, Word) or presentation(slide).
Create a template. Load in new templates. The rticles
package has
templates for academic journals.
The outline (name the chunks).
Help/Markdown Quick Reference
Add a code chunk wih Ctrl+Alt+I
Rendering R Markdown
Knit or preview. For pdf, need LaTeX (install).
Adding runtime:shiny
generates a Shiny report. Launch the interactive
app.
Publish reports online.
Compile notebook
File/Compile Notebook for R script. The script becomes a report (Word,
PDF, HTML).
RStudio’s LaTeX editor
Install LaTeX.
Open a .tex file in RStudio. RStudio has limited options to edit LaTeX;
enough to write and compile.
The preview window is linked to the source window. If we click on a
character in the source window, press Ctrl+click: the corresponding
character is highlighted in the preview window. Vice-versa.
Tools/Global options/Sweave to change the LaTeX options.
Shiny
The server is online.
shiny.rstudio.com
When we create a Shiny app, we create two files: ui.R and server.R
Run App (the app) or Ctrl+Shift+Enter
Publish Shiny apps
Need an account and the shinyapps
package.
devtools::install_github('rstudio/shinyapps')
Deploy the local app online. Unique URL. Monitor usage, view logs,
archive or delete the app. Max 5 apps at a time for free. Paid account.