# -----------------------------------------------------------------------
# Title: title
# Author: William Murrah
# Description: description
# Created: Monday, 23 January 2023
# R version: R version 4.2.2 (2022-10-31)
# Project(working) directory: /Users/wmm0017/Projects/QMER/statistical-thinking
# -----------------------------------------------------------------------
R Script snippets
One of the many features of RStudio that make R coding easier is the ability to use code snippets, which expand the general auto complete options for certain common code forms. For example, if you type lib
in the RStudio console or script editor you will see an auto complete menu pop up with a snipped for the library()
function. This would allow you to select this snippet and it would insert library(package)
at the cursor, with the word “package” highlighted. You could then type in the name of the package you wanted to load and hit tab to complete the snippet. See here for more about RStudio snippets.
You can also create your own snippets, and I want to show how to create a R code script header that I use often. This allows me to start typing the word script
at the beginning of an R script and RStudio inserts a header template like this:
Then, I can insert a title, and description and I have a nice header with important information.
To set this up first copy the text below:
Then go to Tools in the RStudio menu, then click Global Options…, click the Code tab go to the bottom and check the Code Snippets box. Then click on Edit Snippets, scroll to the bottom. Make sure you skip a blank line at the bottom and paste the above code, making sure to replace YOUR NAME
with your name. Tab spacing and alignment are important. The word snippet should be flush with the left margin, and all other lines should be indented two spaces. If the snippet you inserted isn’t highlighted the way the ones just above it in the Edit Snippets window, you likely have a spacing error. Once you have this entered correctly, hit Save, then Ok. Now you should be able to start typing the word script inside an R script and get the script snippet.
See the following video for a demonstration: