Using snippets in RStudio

R
Rstudio
Author
Published

October 7, 2024

Introduction

This post is about using snippets, a really handy feature in Rstudio that can help you save time and cut down on repetitive coding. Despite using Rstudio for over 10 years, I somehow just found out about this feature! I stumbled upon it while reading this blog post about git. This video gives a good overview of snippets and how to use them in Rstudio.

What is a snippet?

A snippet is just a text macro that lets you easily insert a chunk of code. This can be handy for longer code chunks that you find yourself repeating a lot. It also can be really useful for when you don’t remember all the options or exact syntax, and don’t want to have to look it up every time.

How do you use a snippet (in Rstudio)

Rstudio comes with some built-in snippets.

  • You can see them by going to Tools > Global Options > code > edit snippets .
  • You can also use the edit_rstudio_snippets() function from the {usethis} package (Wickham et al. 2024).

You can edit the snippets or add your own via either method.

To use a snippet, you can just start typing the snippet name and it will show up in the code completion list. If your snippet has variables, hit tab to cycle through them and modify them. A nice feature is that if the same variable appears multiple times in the snippet, you only need to type it in once!

Example snippets

Ordered barplots

I often want to make a horizontal barplot in {ggplot2} , with the categories on the y-axis in decreasing order by their values. This isn’t super complicated, but it is a lot of repetitive typing. Here is a snippet that accomplishes this:

# horizontal barplot ordered in decreasing order by x variable
snippet barplot_horizontal
    ggplot(aes(x = reorder(${1:xvar},${2:yvar}), y = ${2:yvar})) +
    geom_col() +
    coord_flip()

Choropleth Maps

The {mapgl} package (Walker 2024) allows you to create really nice-looking Mapbox maps in R, including choropleths. However, the exact syntax is a little long to remember if you’re not using it a lot, so I made a snippet so I could easily insert the code. This is a good example where the same variable appears multiple times in the code chunk, but I only need to type it in once using the snippet.

# mapboxgl choropleth
snippet mapgl_choropleth
    mapboxgl(mapbox_style("light"), bounds = ${1:data_source}) |>
    add_fill_layer(id = "${2:layer_name}",
    source = ${1:data_source},
    fill_color = interpolate(
    column = "${3:column_to_plot}",
    values = c(unname(quantile(${1:data_source}$ ${3:column_to_plot},0.10)),
    unname(quantile(${1:data_source}$ ${3:column_to_plot}, 0.9))),
    stops = c("lightblue", "darkblue"),
    na_color = "lightgrey"
    ),
    fill_opacity = 0.5,
    popup = ${3:column_to_plot}
    ) |> 
    add_legend(
    "${3:column_to_plot}",
    values = c(unname(quantile(${1:data_source}$ ${3:column_to_plot},0.10)),
    unname(quantile(${1:data_source}$ ${3:column_to_plot}, 0.9))),
    colors = c("lightblue", "darkblue")
    )

Summary

I hope you found this information useful and are able to incorporate snippets into your Rstudio workflow!

SessionInfo

R version 4.4.1 (2024-06-14)
Platform: x86_64-apple-darwin20
Running under: macOS Sonoma 14.6.1

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.4-x86_64/Resources/lib/libRblas.0.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.4-x86_64/Resources/lib/libRlapack.dylib;  LAPACK version 3.12.0

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: America/Denver
tzcode source: internal

attached base packages:
[1] stats     graphics  grDevices datasets  utils     methods   base     

loaded via a namespace (and not attached):
 [1] htmlwidgets_1.6.4 compiler_4.4.1    fastmap_1.2.0     cli_3.6.3        
 [5] htmltools_0.5.8.1 tools_4.4.1       rstudioapi_0.16.0 yaml_2.3.10      
 [9] rmarkdown_2.28    knitr_1.48        jsonlite_1.8.9    xfun_0.48        
[13] digest_0.6.37     rlang_1.1.4       renv_1.0.9        evaluate_1.0.0   

References

Walker, Kyle. 2024. “Mapgl: Interactive Maps with ’Mapbox GL JS’ and ’MapLibre GL JS’ in r.” https://CRAN.R-project.org/package=mapgl.
Wickham, Hadley, Jennifer Bryan, Malcolm Barrett, and Andy Teucher. 2024. “Usethis: Automate Package and Project Setup.” https://CRAN.R-project.org/package=usethis.