---

This site uses cookies. Read more.

Welcome to the second part of R Studio shortcuts and tips!


If you have not yet read r studio shortcuts and tips – part one, I strongly recommend checking it out before proceeding further.

Code Inserting Tricks

Operators and sections

Let’s start with some shortcuts that are easy and very useful! If you want to speed up writing 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. 🙂

Code Snippets

Using snippets

Are you tired of writing the same chunks of code over and over, remembering all the brackets and required parameters for functions?
A great way to avoid writing too much, especially a common code, is to use code snippets.
They are perfect for automation of inserting boilerplate code, but also 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).

How to use them?
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.

Creating custom Snippets

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 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 paste function to insert a comment with a current date into code.
Its execution resolves into something like this:

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

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

Searching

So, by now if you don’t have a lot of code yet, you should at least be able 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 searching 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 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.

Editing with multiple cursors

There is a possibility in R-Studio 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 pressed direction. 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 and not be easy to operate on your first try, but knowing it is there can save you time when you encounter repetitive multi-line tasks. Try playing around with it for some time.
Below you can see an example of how the use-case scenario 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 all the file you can also limit area for searched phrase by selecting a part you are interested in and checking the box with “In selection” option.


Addins

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

They 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. The former inserts text into the console /source pane or can transform text within the source pane.  The latter are interactive shiny applications launched inside RStudio which may also perform transformations like text macros, but their possibilities are much more extensive.

Test out some addins

To quickly try addins you can install some examples from R-Studio Github.
devtools::install_github("rstudio/addinexamples", type = "source")
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).

Get more and make your own!

If you just want to check out more of them try the addinslist package by Dean Attali.
Would you like to create your own addins, you can find more information on how to do it here.


That is all for the second part of this article. There is obviously more to explore in this topic and I hope you got inspired to make further explorations and experiments on your own. If you end up with something useful as a result – be it snippet, addin or just something useful that I did not mention why not share it in a comment? It would be lovely!

Did you know all of it? That’s cool!
Consider sharing this with someone who could benefit, like a friend who is just starting with R!

Thank you for reading, I wish you all to have a very productive workflow with R Studio!