RStudio IDE Tips and Tricks - Shortcuts You Must Know (Part 2)
<p style="text-align: left;"><em><strong>Updated</strong>: June 7, 2022.</em></p> Welcome to Part Two of RStudio Tips and Tricks! If you have not yet read RStudio shortcuts and tips - part one, we strongly recommend checking it out before proceeding further. <blockquote>Are you an avid Excel user? <a href="https://appsilon.com/r-and-excel/">Here's how you can combine R and Excel with ease</a>.</blockquote> Today we'll focus on more advanced RStudio tips and tricks, including: <ul><li><a href="#codeinsertion">Code Insertion</a></li><li><a href="#codesnippets">Code Snippets</a></li><li><a href="#searching">Searching</a></li><li><a href="#editing">Editing with Multiple Cursors</a></li><li><a href="#addins">Addins</a></li></ul> Note: At the time of writing this article, Posit PBC was RStudio PBC. We use RStudio and Posit interchangeably in this text (e.g. RStudio Connect == Posit Connect). <hr /> <h2 id="codeinsertion">Tips for Code Inserting in RStudio</h2> <h3>Operators and sections</h3> Let’s start with some basic RStudio Tips and Tricks - shortcuts. These are easy to understand and very useful! If you want to speed up writing the most common operators you will definitely love these: <b>Alt + (-) </b>for inserting assignment operator <b><code><-</code> </b>and <b>Ctrl + Shift + M </b>for a magrittr operator (aka pipe) <code>%>% </code>The nice thing about those two is the fact that spaces are inserted along with the operator. <b>Ctrl + Shift + R </b> 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 <code>{}</code> or in Rmd) with<b> Alt + L - </b>collapse<b> </b><b>Alt + Shift + L -</b> open To collapse or open <b>all</b> sections, instead of the active one, just replace <b>L</b> with <b>O </b>on those shortcuts. <img class="wp-image-1868 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b023163b3143b587a32e2f_insertcode7.gif" alt="Image 1 - Section insertion" width="936" height="389" /> Image 1 - Section insertion <h3>Function/Variable Extraction</h3> If you have written a statement that you would like to convert into a function, there's no need to start from scratch. Select it and try <b>Ctrl + Alt + X</b> - shortcut for “extract into function”. You only need to provide the function name, all necessary inputs will be filled in automatically. There is also a similar shortcut for a variable extraction available with <b>Ctrl + Alt + V. </b>Here you have an example of usage. <img class="wp-image-1867 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b02317d6ff13a92d206371_extract_fun_var.gif" alt="Image 2 - Extracting functions and variables" width="936" height="422" /> Image 2 - Extracting functions and variables <h3>Renaming in Scope</h3> 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 pressing <b>Ctrl + Shift + Alt + M. </b>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. We find it to be easier to remember as an extension of the magrittr operator shortcut, so <b>Pipe</b> <b>+</b> <b>Alt</b>. <img class="wp-image-1866 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b023196ee3169213cad340_rename_in_scope.gif" alt="Image 3 - Renaming" width="936" height="400" /> Image 3 - Renaming <h2 id="codesnippets">Code Snippets</h2> <h3><b>Using snippets </b></h3> <img class="wp-image-1916 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0231ac51a6e88355a5a12_shinyapp_snippet.gif" alt="Image 4 - Built-in code snippets" width="634" height="302" /> Image 4 - Built-in code 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 and 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: <ul><li>Declarations - lib, req, fun, ret, mat </li><li>Loops - for, while, switch </li><li>Conditionals - if, el, and ei for conditionals</li><li>Apply family functions - apply, lapply, sapply, etc. </li><li>S4 classes/methods definitions - sc, sm, and sg.</span></li><li>Shiny App template - shiny app</li></ul> <img class="wp-image-1865 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0231c536cc909ce52bdbe_snippets4.gif" alt="Image 5 - More snippets" width="578" height="507" /> Image 5 - More snippets 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 we used insertOperatorsExample, a very simple custom snippet we created on the first gif showing operator shortcuts. <h3>Creating custom Snippets</h3> For customizing or creating your own snippets use the <b>Edit Snippets</b> button under the Snippets section in <b>Tools -> Global Options -> Code</b> 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. <pre><code class="language-r">snippet mat matrix(${1:data}, nrow = ${2:rows}, ncol = ${3:cols})</code></pre> <pre><code class="language-r">snippet fun ${1:name} <- function(${2:variables}) { ${0} }</code></pre> $ 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 the 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. <pre><code class="language-r">snippet ts `r paste("#", date(), "------------------------------\n")`</code></pre> It runs the paste function to insert a comment with a current date into the code. Its execution resolves into something like this: <img class="wp-image-1869" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0231c9bd6df84c7f6f471_tssnippet.webp" alt="Image 6 - Custom snippets" width="490" height="34" /> Image 6 - Custom snippets Equipped with knowledge lets quickly create a custom snippet for inserting pipe, but instead space we will have a new line right after it: <pre><code class="language-r">snippet pipe `r paste(" %>%\n")`</code></pre> <img class="wp-image-1915 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0231de8fe2e8669b0dc62_pipesnippet-1.gif" alt="Image 7 - Custom snippets (2)" width="448" height="186" /> Image 7 - Custom snippets (2) <h2 id="searching">Searching in RStudio</h2> 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 <b>Ctrl + (.) </b>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. <img class="wp-image-1864 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0231eae9161a5923d478d_searching2.gif" alt="Image 8 - Searching" width="918" height="415" /> Image 8 - Searching If you need more robustness, use <b>Ctrl + Shift + F</b> 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. <img class="wp-image-1863 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b0231fa09b709872f2d575_searching2-1.gif" alt="Image 9 - Finding in files" width="1020" height="512" /> Image 9 - Finding in files If you want to search only inside an active source tab you can use the find bar with <b>Ctrl + F</b> which allows several additional options like replacing texts and searching inside selected parts 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. <h2 id="editing">Editing in RStudio with Multiple Cursors</h2> 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 <b>Ctrl + Alt + (Up/Down)</b> to create a new cursor in the pressed direction. If you want to quickly select more lines use <b>Alt</b> and drag with the mouse to create a rectangular selection, or <b>Alt + Shift</b> 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. <img class="wp-image-1862 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b023210b330f2efeac466d_multiple-line-editing4.gif" alt="Image 10 - Editing with multiple cursors" width="1503" height="818" /> Image 10 - Editing with multiple cursors Another way is to use the Find/Replace toolbar from the previous paragraph to place multiple cursors. Just search for a phrase and press the <b>All </b>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 files you can also limit the area for searched phrases by selecting a part you are interested in and checking the box with the <b>"In selection"</b> option. <img class="wp-image-1913 size-full" src="https://webflow-prod-assets.s3.amazonaws.com/6525256482c9e9a06c7a9d3c%2F65b02323f92b3d80176e1988_multiple-line-editing4_1.gif" alt="Image 11 - Find and replace" width="996" height="555" /> Image 11 - Find and replace <h2 id="addins">Addins</h2> 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. 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 <i>Addins</i> 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. <h3>Test out some addins</h3> To quickly try addins you can install some examples from R-Studio Github. <pre><code class="language-r">devtools::install_github("rstudio/addinexamples", type = "source")</code></pre> <span style="font-weight: style=;">It will give you a text macro for inserting </span><code>%in%</code> operator, as well as three shiny gadgets for a small sneak, peek of what's possible. As we 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). <h3>Get more and make your own!</h3> 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. <hr /> That is all for the second part of RStudio Tips and Tricks. There is obviously more to explore on this topic and we 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 snippets, an addin, or something useful that we did not mention please share it in the comments. <blockquote>Want to use R and Python together? <a href="https://appsilon.com/use-r-and-python-together/">You can, and it's easier than you think!</a></blockquote> 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, we wish you all to have a very productive workflow with R Studio!