TIL about code snippets in RStudio

Last updated: 2023/07/28

I recently learned about code snippets in RStudio (ignore the strikethrough). As the name suggests, they are snippets of code that you can quickly insert into your source code in the source pane of RStudio. There are two ways to add code snippets:

  1. Click on the following: Tools -> Global Options -> Code -> Edit Snippets (near the bottom)

  1. Edit the ~/.config/rstudio/snippets/r.snippets file, where ~ is your HOME directory.

As an example, I have added the timeit code snippet. The spaces at the front of the code are tabs.

snippet timeit
    start_time <- Sys.time()
    # add your code here
    Sys.sleep(5)
    end_time <- Sys.time()
    end_time - start_time

After saving the code snippet, type timeit in the source pane and press shift+tab and the code snippet will be automatically inserted!

You can even have snippets of code that execute. For example, the timestamp snippet, which is included by default, will add a timestamp. Just type ts and shift+tab. Put code to be executed between backticks, as per the example below.

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

Another cool trick is to define variables in snippets using the syntax {1:varname}. What will happen when you press shift-tab is that the code snippet will be inserted and you will be prompted to type an entry for varname. For example the lapply snippet (included by default) will ask you enter the list and the function. After you enter the list name, you can press tab to shift to entering the function name.

snippet lapply
    lapply(${1:list}, ${2:function})

Since I'm constantly forgetting code syntax, code snippets are great!

Print Friendly, PDF & Email



Creative Commons License
This work is licensed under a Creative Commons
Attribution 4.0 International License
.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.