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:
- Click on the following: Tools -> Global Options -> Code -> Edit Snippets (near the bottom)
- 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!
This work is licensed under a Creative Commons
Attribution 4.0 International License.