Sharon Machlis
Contributing Writer

How to use RStudio code snippets

how-to
May 23, 20195 mins

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
Credit: 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")

Iย 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ย mydf,ย myxcol, 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 playlist on YouTube.