Code snippets in RStudio

editor
shortcut
rstudio
Author

Nicolas Casajus

Published

February 27, 2024

Using snippets

A code snippet is a text shortcut that is used to insert a predefined chunk of code. It’s like super-completion. The RStudio IDE contains a lot of predefined code snippets. For instance:

  • src can be used to insert source("file.R")
  • lib can be used to insert library(package)
  • tapply can be used to insert tapply(vector, index, function)

To use a snippet, enter the shortcut of the snippet (for example src) and press SHIFT + TAB to insert the corresponding chunk of code (for example source("file.R")).

Note

Code snippets are language-specific meaning that they will work only with the appropriate language. For instance, in Markdown documents (.md, .Rmd and .qmd files), by using the snippet ![ (and SHIFT + TAB) you will write the markdown syntax to insert an image: ![label](location). This snippet won’t work inside .R files.

Figure 1. How to use a snippet

Use the key TAB to navigate inside the code snippet. In the snippet ![label](location), label and location are two variables. Once the snippet is created the cursor is in label. Use TAB to go to location.

You will find a list of predefined snippets in Tools > Edit Code Snippets...

Customizing snippets

You can easily add your own code snippets by editing the code snippets editor in Tools > Edit Code Snippets...

Figure 2. RStudio code snippets

Let’s add a snippet that will create a new code section for us:

snippet sec
    ## ${1:Title} ----
    
    ${0}

This snippet has two variables: ${1:Title} and ${0}.

When we write sec and press SHIFT + TAB a new section will be created. The cursor will be on Title and after pressing TAB we go to the next line.

Figure 3. Custom snippet in action

When creating a new snippet, make sure to select the appropriate language (Figure 2).

Tip

  For further information visit this article.