video

How to use RStudio code snippets

Save time by storing your best and most-used code in RStudio snippets.

Do More With R [video teaser/video series] - R Programming Guide - Tips & Tricks
Thinkstock

“Code snippets” is just another phrase for macros or templates—and a great way to save time when writing scripts. Snippets not only cut down on keystrokes while you’re coding; they also save you search time trying to dig up that complex code you got just right six months ago but no longer remember.

Here’s how they work—and how you can make your own—in RStudio.

Sample graph

Since I get a little tired of the ubiquitous mtcars and iris data sets for examples, I’ll use some information about IT Manager salaries (from a Computerworld salary survey) for this demo. Here’s my data frame if you’d like to follow along.


salaries <- data.frame(
Year = c("2017", "2016", "2015", "2014", "2013", "2012") ,
Salary = c(99053L, 96413L, 95619L, 92724L, 91686L, 90165L)
)

The black-and-white graph is what a ggplot2 default bar chart of this data looks like.

default graph in ggplot2 Sharon Machlis, IDG

The default graph in ggplot2.

The color version is what I wanted my final graph to look like.

tweaked ggplot2 graph Sharon Machlis, IDG

My ggplot graph after tweaks.

I spent a fair amount of time tweaking the graph code. I changed bar colors, added labels, included commas on the y axis, centered the title and subtitle …. I would never remember how to do all that again without looking it up. 

Here’s the graph code. Note that you need the scales package installed and loaded in addition to ggplot2.


ggplot(salaries, aes(x=Year, y=Salary)) +
geom_col(color = "black", fill="#0072B2") +
theme_minimal() +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line = element_line(colour = "gray"),
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)
) +
scale_y_continuous(label = comma) +
xlab("") +
ylab("") +
geom_text(aes(label=scales::dollar(Salary)), vjust=1.5, colour="white", position=position_dodge(.9), size=5) +
ggtitle("IT Manager Salaries by Year", subtitle = "Source: Computerworld IT Salary Survey")

could save the graph in a file, and hope I remember where the file is. Or, I could make a function with all these defaults, but that’s not always my preferred option if I want to do a bit more tweaking next time. 

Instead, I made a code snippet.

RStudio comes with some of its own built-in snippets. When I create my own to add to the built-in ones, I name them starting with my_underscore. That way, when I start typing my_ in my scripting window, they show up in a drop-down list.

snippet dropdown Sharon Machlis, IDG

Dropdown list for custom and built-in RStudio code snippets.

I called my bar graph snippet my_custom_barchart. I’ll type that, select it, and what pops up is all my code for the graph.

graph code from snippet Sharon Machlis, IDG

Graph code generated by my code snippet.

And not only the code. There are variables in this snippet. My cursor automatically jumped to the first variable, which I called mydf. I can change that to the name of the data frame that I called salaries. If I hit the tab key, my cursor jumps to the next variable, which I called myxcol. I would change that to Year. When I hit tab again, there are two places where myycol variable is used. When I change that to Salary on the first one, the second one changes too. You can see how this works in the embedded video above.

Snippet format

Each snippet starts with the word snippet at the beginning of a line, followed by a space, and then the name of the snippet. All the snippet code below has to be indented with a tab. If you use spaces to indent the code, the snippet won’t work.

Otherwise, you mostly write the code you want, as usual. Once each code line starts with a tab, it can have additional spaces.

To add a variable, start with a dollar sign and open curly brace, then the number of your variable, a colon, the name of the variable, and the closing brace, such as ${1:myvar}. You can see that in the first code line of my snippet following the title, where I defined variables mydfmyxcol, and myycol. Your cursor will jump from variable to variable based on the numbers of the variables: Here 1, 2, and 3 for graph variables, plus 4 and 5 for title and subtitle. If you’re using a variable more than once, you give it the same number and name in multiple places in your code.

This is my complete snippet:

snippet my_custom_barchart
ggplot(${1:mydf}, aes(x=${2:myxcol}, y=${3:myycol})) +
geom_col(color = "black", fill="#0072B2") +
theme_minimal() +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(), axis.line =
element_line(colour = "gray"),
plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5)
) +
scale_y_continuous(label = comma) +
xlab("") +
ylab("") +
geom_text(aes(label=scales::dollar(${3:myycol})), vjust=1.5, colour="white",
position=position_dodge(.9), size=5) +
ggtitle("${4:mytitle}", subtitle =
"${5:mysubtitle}")

Code snippets live in a special RStudio text file that you can get to with the menu commands Tools > Global Options > Code > Edit Snippets.

Fortunately, though, you don’t have to go through four menu layers to get to the snippet file. The usethis package has a function edit_rstudio_snippet() that will pop open the file for editing.

You can add your custom snippets anywhere in the file—at the top, at the bottom, or in the midst of the snippets included with RStudio. Save that r.snippet file, and you’re done.

For more on snippets, watch the video above and check out RStudio’s Code Snippets article by J.J. Allaire. For more R tips, head to the Do More With R page at InfoWorld or the Do More With R playlist on YouTube.

Copyright © 2019 IDG Communications, Inc.