2 min read

Using Snippets in RStudio as Keyboard Shortcuts

Code Snippets are a useful feature of RStudio that many people don’t know about. The RStudio Blog post gives good instructions on how they can be used, but I thought I’d share how I use them.

Here are some of the ways I use snippets:

Loading Magrittr

One of my favorite R functions is the pipe operator, %>%, from the Magrittr package. There’s already a keyboard shortcut, Ctrl+Shift+M, for this function. However, it’s really annoying when I first try to use it and I get the error message that the function could not be found. All that is required is to then call library(magrittr), but that’s a lot of typing (not really, but it feels that way). So I created a snippet, lbm, to speed this up, shown below.

snippet lbm
    library(magrittr)

Now if I type lbm, then press tab, it inserts library(magrittr) for me.

Loading other packages

Similar to Magrittr, there are other packages that I often need to load. So I can create a snippet in the exact same way as above (these two sections could really just be one section). Right now I have snippets to load testthat (lbtt) and three of my own packages: lbcf for ContourFunctions, lbtf for TestFunctions, and lbgp for GauPro.

Shortcuts for functions with long names

A similar way I use snippets are as shortcuts for functions with long names. I love the microbenchmark package and function, but it’s name, especially typing it when the package isn’t loaded, is far too long. I created a snippet, mb, that is much shorter. I also created another one, mbc, for the mbc function in my comparer package. Both are shown below.

snippet mb
    microbenchmark::microbenchmark

snippet mbc
    comparer::mbc