[This article was first published on r – Appsilon Data Science | End­ to­ End Data Science Solutions, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Updated: May 2020 by Appsilon Data Science

## How to Work Faster in RStudio

In this article we have compiled many of our favorite RStudio keyboard shortcuts, tips, and tricks to help increase your productivity while working with the RStudio IDE. We’ll also provide information about supplemental tools and techniques that are useful for data scientists that work with R.

Here’s what we cover:

*Note: Although we present both options in the gifs (PC and Mac shortcuts), we refer to PC shortcuts in the text. If you are a Mac user most of the shortcuts fall under this dependence:

Ctrl == ⌘ Command  &&  Alt == ⌥ Option

Keep in mind that in some cases Ctrl will also be the control key on Mac which can be confusing. You can always look up the proper shortcuts on RStudio’s website or within RStudio itself with:

Option+Shift+K (Alt+Shift+K)

Depending on your work, you will use at least a few RStudio panes on a regular basis. Learning how to change focus between those utilized the most in a quick manner, and without using your pointing device, is a crucial skill for speeding up your workflow. It is achieved by pressing Ctrl (in this case also Control on Mac) and a number corresponding to the desired pane. By adding a Shift to the combination you can also toggle maximize pane for the one that you are switching to at the same time, very handy if you need a broader perspective. The only pane with a different access shortcut is the terminal (Shift+Alt+t). Preset windows: Help(3), History(4), Plots(5), or Environment(8). The two that you will be mostly jumping between frequently are Source Editor (1) and Console (2). Let’s now discuss how you can improve how you work in those.

## How to Use Shortcuts in RStudio

Usually, the first thing you have to do when you start working is creating some code.  It is crucial to be aware that there are some features that can make it both easier and faster. Even basic tricks can have a great impact once you master using them, especially when combined together.

#### Code Completion

A suggestion list will pop up as you type or can be accessed manually by either pressing Tab or Ctrl + Space. You can adjust those settings in Global Options ->  Code -> Completion. To fill in the suggested phrase you have to press either Tab or Enter, pressing Ctrl + Space with auto-completion list open will close it. You can navigate through the suggestion list with arrows or just hover over the item before filling it in.

If the list is too long, try providing more letters to narrow it down. Beside auto-completing functions and variables, you can also insert snippets. We will get back to discuss those later. It’s good to be aware that auto-completion in R, as well as some search fields, supports fuzzy matching which means that you don’t really have to type all the letters, you can skip any of them as long as those typed are in order and identify what you are looking for. It is especially useful for long function names that you use often. Mastering this will allow you to type code much faster. Note that for fuzzy matching to work with auto-completion, suggestion popup must be already active. In case it doesn’t behave as you would expect, try tweaking it in code completion options.

#### Paths

If you need to type a path, you can use file path auto-complete which can be brought up by pressing the auto-completion shortcut (Tab or Ctrl + Space) from a pair of double or single quotes.

By default it starts in your working directory, you can navigate from the root location like in shell console starting with “/”, or step up levels in the directory tree by stacking “../”

## How to Execute and Format Code in RStudio

Executing code in your scripts can be very easy with the following shortcuts:

• Ctrl + Enter – Will run current line and jump to the next one, or run selected part without jumping further.
• Alt + Enter – Allows running code without moving the cursor to the next line if you want to run one line of code multiple times without selecting it.
• There is also Ctrl + Alt + R to run whole script and
• Ctrl + Alt + B/E combinations to run it from Beginning to the current line and from the current line to the End.

If you want to make your code look better quickly try using the following:

• Ctrl + I to fix lines indentation
• Ctrl + Shift + A for complete reformat of the selected part of a code

If you are not happy with the outcome of those you can always undo the changes. If you look for a more flexible solution for styling check out the styler package.

You may also benefit from remembering these super helpful shortcuts:

Moving lines of code up and down is easily achieved with an Alt + Up/Down combination; there is no need to cut and paste. You can move a single active line that way, or even whole selection. If you need to remove something Ctrl + D will delete current line/selection in no time.

## Console History & History Pane

Everything that you passed to the console doesn’t have to be typed again. Accessing previously executed lines is as easy as navigating with the up arrow and down arrows to cycle between them in chronological order. If you want more visual feedback you can press Ctrl + Up arrow to get a list of last commands. If you combine it with typing in a part of the searched phrase you can narrow it down and easily find even complicated commands that are buried deep in the history. It will also override autocomplete popup if its active. Note: searching console history doesn’t support fuzzy matching so you have to be exact. If you want to clear your console use Ctrl+L, the command history will be preserved.

There is also a History pane(4) which stores executed commands. It allows search, easy selection of the ones you need (pick range with shift or gather individual positions with ctrl). Then easily insert them back into the console (Enter) or source file (Shift + Enter). The latter helps you avoid copying multiple commands from console to source manually which is troublesome due to line signs “>” that get copied as well and would otherwise have to be removed.

## Dealing with Tabs

If you find yourself working on more than one tab in a source editor, you might find it helpful to switch between them with Ctrl+Tab and Ctrl+Shift+Tab combinations. It will allow you to jump to the next and previous tab respectively, there is another way to do this with Ctrl + F11/ F12 if it suits you better. It is also possible to jump to the first or last one by adding Shift to those. Last option that is quite interesting is navigating through tabs in the order they were accessed with Ctrl + F9/F10.

#### Going through tabs back and forth:

Closing a current tab is easy with Ctrl + w. It is a much better choice than using those small “x” buttons on the right side of your tabs. If you get to the point where you have a huge amount of tabs open you can:

Close All  | Ctrl + Shift + w (+ Alt to keep the currently open one):

Or if you prefer to keep a lot of tabs open, you can search through your open tabs with Ctrl + Shift + . Be exact! No fuzzy matching here. This search can also be activated with “>>” icon on tabs bar.

The above shortcuts are also accessible from the File dropdown menu – this can come in handy while using RStudio browser session or simply if you forget them.

## Code Inserting Shortcuts in RStudio

#### Operators and sections

Let’s start with some shortcuts that are easy and very useful! If you want to speed up typing the most common operators you will definitely love these:

Alt + (-) for inserting assignment operator <-

and

Ctrl + Shift + M for a magrittr operator (aka pipe)  %>%

The nice thing about those two is the fact that spaces are inserted along with the operator.

Ctrl + Shift + R  is an easy way to create foldable comment sections in your code.

It’s worth it to know about the appliance of those sections for code externalization with knitr:read_chunk() function. If you want to know more about that check the details.

You can open/collapse those comment sections (as well as other kinds of sections e.g. inside curly braces {} or in Rmd) with

Alt + L – collapse

Alt + Shift + L – open

To collapse or open all sections, instead of the active one, just replace L with O on those shortcuts.

#### Function/Variable Extraction

If you have written a statement that you would like to convert into a function, don’t start from scratch. Select it and try Ctrl + Alt + X – shortcut for “extract into function”. You only need to provide the function name, all necessary inputs will be filled automatically. There is also a similar shortcut for a variable extraction available with Ctrl + Alt + V. Here you have an example of usage.

#### Renaming in Scope

If you have to change a variable name in multiple places but you are afraid that ‘find and replace’ will mess up your code, you should be aware that it is possible to rename in scope only. It is achieved by selecting the function or variable we want to change and press Ctrl + Shift + Alt + M.

It will select all occurrences in scope, you will have to just type a new name.

Yes, the shortcut is long, but it can be helpful. I find it to be easier to remember as an extension of the magrittr operator shortcut, so Pipe + Alt.

## Using Code Snippets in RStudio

Are you tired of writing the same chunks of code over and over and having to remember all of the brackets and required parameters for functions? A great way to avoid writing so much, especially a common code, is to use code snippets.

#### What are code snippets?

Code snippets are pieces of re-usable boilerplate code.

Snippets are perfect for automatically inserting boilerplate code and avoiding the duplication of simple tasks. If you are looking for a way to speed up writing large parts of code when time is limited (e.g. live coding during a presentation), code snippets can be very useful.

#### How do I use code snippets?

Snippets can be recognized on your auto-completion list by a {snippet} tag.

Write the snippet name, press Shift + Tab, or Tab twice to use it. If your input is needed to complete it – just fill out positions with elements that are important. You can cycle through them with Tab.

Some of the snippets which are available by default include:

• Declarations – lib, req, fun, ret, mat
• Loops – for, while, switch
• Conditionals – if, el, and ei for conditionals
• Apply family functions – apply, lapply, sapply, etc.
• S4 classes/methods definitions – sc, sm, and sg.
• Shiny App template – shinyapp

And that’s just for R! There are also snippets for other languages and it is very easy to customize and define your own!

You might have noticed that I used insertOperatorsExample, a very simple custom snippet I created on the first gif showing operator shortcuts.

## How to Create Custom Code Snippets in RStudio

For customizing or creating your own snippets use Edit Snippets button under Snippets section in

Tools -> Global Options ->  Code

To understand better how you can create your snippets let’s take a look at a matrix and function snippets declarations code as an example.

 snippet mat matrix(${1:data}, nrow =${2:rows}, ncol = ${3:cols}) snippet fun${1:name} <- function(${2:variables}) {${0} } 

$is used as a special character to denote where the cursor should jump after completing each section of a snippet. Inside the brackets, we have a field index (order in which the cursor will jump after pressing tab), 0 is used as the last field, and the text after a colon is used as information on what should be placed in that spot. In order to insert a literal “$” inside a snippet, it must be escaped as \\$.

Snippets, besides generating code templates, can also run R code. It allows you to create dynamic snippets. By using r expr anywhere in your snippet your R code will be executed when the snippet is expanded, and the result inserted into the document.

As an example take a look at the timestamp snippet declaration that is available by default.

 snippet ts r paste("#", date(), "------------------------------\n") 

It runs a paste function to insert a comment with a current date into code. Its execution resolves into something like this:

Equipped with this knowledge, let’s quickly create a custom snippet for inserting pipe, but instead of a space we will have a new line right after it:

 snippet pipe r paste(" %>%\n") 

So, if you don’t have a lot of code yet, you have the tools to quickly generate it.

The next question is then, how to find things that you are looking for quickly.

There are several available options for search that you can use.

Go to file function Ctrl + (.) allows you to quickly search your project for a file or function and jump directly to it. It supports fuzzy matching so it’s easy to find what you need.

If you need more robustness, use Ctrl + Shift + F to call the Find in Files window which allows you to search through files in a directory that you can specify (even outside the project). You can jump between elements you found by double-clicking them in the Find in Files window which opens next to the console.

If you want to search only inside an active source tab you can use the find bar with Ctrl + F which allows several additional options like replacing texts and searching inside a selected part of code only. It can also be useful for multiple cursor editing – see the section below.

We have already covered more methods in part 1 – search within console history and searching through your tabs. You can refer to it if you want to get more details on those.

## How to Edit With Multiple Cursors in RStudio

In RStudio, it is possible to write and edit in more than one place at a time. There are a couple of ways to create multiple cursors. You can press Ctrl + Alt + (Up/Down) to create a new cursor in the direction in which you press. If you want to quickly select more lines use Alt and drag with the mouse to create a rectangular selection, or Alt + Shift and click to create a rectangular selection from the current cursor position to the clicked position.

This way of editing may look intimidating  at first, and may not be easy to operate initially. However, knowing it is there can save you time when you encounter repetitive multi-line tasks. Try playing around with using multiple cursors and see how it feels.

Below you can see an example of how using multiple cursors might look:

Another way is to use the Find/Replace toolbar from the previous paragraph to place multiple cursors. Just search a phrase and press the All button to select all matching items. It will create a cursor for each matching phrase. If you don’t want to search throughout the entire file you can also limit the area for a searched phrase by selecting a part you are interested in and checking the box with the “In selection” option.

## How to Use R Addins

R Addins are a broad topic that could fill a blog post on their own. We just want to give you a brief introduction to this concept.

R Addins make it possible to execute R functions in an interactive way right from within the RStudio. Addins are distributed as R packages and can be launched either through the Addins dropdown on the toolbar or through assigned keyboard shortcuts.

We can distinguish two types of addins. Those are text macros and Shiny gadgets. Text macros insert text into the console / source pane or can transform text within the source pane.  Shiny gadgets are interactive Shiny applications launched inside RStudio which may also perform transformations like text macros, but their possibilities are much more extensive.

To quickly try addins you can install some examples from RStudio Github.

It will give you a text macro for inserting %in% operator as well as three shiny gadgets for a small sneak peek of what’s possible.

As I mentioned, you can assign a keyboard shortcut to an addin the same way as you do it with regular shortcuts.  You can find them easily by filtering “Addin” (all of them have their scope set like that).

If you want to check out more of them try the addinslist package by Dean Attali.

## Bonus RStudio Tips

#### Tip: Use vim Settings

Keep your hands in one place! It’s a powerful method for programmers. Examples: dd to delete the whole line, 7dd to delete 7 lines, navigate, macros, jumping around whole words instead of letters.

#### Tip: Use .RProfile

When you develop an R package, it’s useful to load frequently used dev packages in the .RProfile file (placed in the main package directory). For example:

 library(devtools) 
 library(testthat) 

This way you can use functions like test(), check() without specific package reference or loading the packages on your own.

#### Do not keep credentials inside your project code. A good practice is to keep them “gitignored” inside the .Renviron file:

 db_password=MySecretPassword 

And use a variable in the code with Sys.getenv(“db_password”).

#### Tip: Use Docker

If you want to keep a consistent environment for your project development within a team, use a dockerized version of RStudio (https://hub.docker.com/r/rocker/rstudio/).

There is obviously plenty more to explore on the topic of improving your RStudio workflow, and we hope you are inspired to pursue further exploration and experiments on your own. If you end up with something useful as a result – be it a code snippet, an addin or just something useful that we did not mention her, why not share it as a comment below? We’ll be updating this page regularly with more RStudio tips.