R Hacks

A list of helpful tips and tricks for coding in R.

Team 346 pol346.com (Princeton Univeristy Department of Politics)princeton.edu/politics

R Studio Modifications

changing theme

RStudio > Preferences > Appearence

Keyboard Shortcuts

Here are some keyboard shortcuts that make coding in R much easier and quicker. A full list can be found online (https://support.rstudio.com/hc/en-us/articles/200711853-Keyboard-Shortcuts) or in RStudio by going to Help > Keyboard Shortcuts Help.

change keyboard shortcuts

First, the trick to make the rest of this handout irrelevant. You can change you keyboard shortcuts by going to Tools > Modify Keyboard Shortcuts. This is super helpful for commands you use all the time that have inconvenient shortcuts. For example, I changed the pipe shortcut from command + shift + M to command + .


option + dash


add a pipe

command + shift + M


view subset of dataframe

mtcars %>% dplyr::select(mpg, cyl) %>% head()
                   mpg cyl
Mazda RX4         21.0   6
Mazda RX4 Wag     21.0   6
Datsun 710        22.8   4
Hornet 4 Drive    21.4   6
Hornet Sportabout 18.7   8
Valiant           18.1   6
# Also View() command will open a new viewer tab in RStudio

quote or parenthesis a line of text

highlight + ( or "

# from this
a long chunk of code you want to add parenthesis or quotes around

# to this
(a long chunk of code you want to add parenthesis or quotes around)
"a long chunk of code you want to add parenthesis or quotes around"

comment out a chunk

highlight, command + shift + c

# this is a chunk of text
# that I want commented out
# that runs for
# multiple lines

create new code chunk

command + option + I

look at the documentation for a function

(in console) ? + the function

Help on topic 'clean_names' was found in the following

  Package               Library
  janitor               /Library/Frameworks/R.framework/Versions/4.0/Resources/library
  insight               /Library/Frameworks/R.framework/Versions/4.0/Resources/library

Using the first match ...

run a single line of code

command + enter

run a line of code you recently ran

(in console) up arrow

pop-up menu of lines you’ve recently run

(in console) command + up arrow

Additionally, if you type the beginning of a recent command in the console and then press command + up, you’ll get a pop-up menu of recent commands that match what you’ve already typed.

history pane

Another way to find recently run code is in the History pane. You can find it on the right of your RStudio window, next to the Environment pane. This stores all the commands you’ve run in your current session. To find a command, you can look it up in the search bar. To transfer these commands to the console, simply double click. To transfer them to your script, highlight what you want and click the To Source button. This allows you to copy code from your console without the annoying plus signs.

knit Rmarkdown

command + shift + K

neaten up code

command + shift + A

# from this
df<-df %>% 
    mutate(x=case_when(y==1~0, y = 3~8,TRUE~NA)) %>%
  filter(x==10|x==20) %>%

# to this
df <- df %>%
  mutate(x = case_when(y == 1 ~ 0, y = 3 ~ 8, TRUE ~ NA)) %>%
  filter(x == 10 | x == 20) %>%
  select(x, y)


R will autocomplete functions and file names as you’re typing. To check that your autocomplete is on, go to RStudio > Preferences > Code > Completion and make sure the appropriate boxes are checked.

When you’re typing and the suggestion box comes up, press tab to insert the first suggestion. You can also call this suggestion box at anytime by pressing tab. Once the suggestion list is up, you can skip letters and as long as they’re in the right order, R will still find the function. For example, if I want to find the ggplot2 package, I type g + tab + p2 and the first suggestion will be ggplot2::.

g # tab to pull suggestion window up
gg2 # tab again to insert the suggestion

Play around with the autocomplete function to get a feel for how it works. This tool is especially useful when you have names that are identical except for the last number or letter and you want to quickly call up the correct file.


R has snippets which will fill in common chunks of code for you. For instance, the fun snippet will give you a template for building a function:

fun # type this and then tab to fill in the first suggestion

# this is the snippet R will give you
name <- function(variables) {

Then, simply press tab to toggle between the different sections to fill in your variables. Snippets give you the correct formatting for the function you’re using as well as being much faster than typing it out. There are also snippets for ifelse statements, for loops, tapply, and many more.

You can also use snippets to run chunks of code you often include. For example, if there are certain packages that you load every time you do a p-set, you can make a snippet to insert them all at once.

To view all current snippets or make your own, go to Tools > Global Options > Code and click Edit Snippets. For example, I made this snippet for simple ggplots.

# coding of the ggplot snippet that I put in "Edit Snippets" section
snippet gg
    ${1:data} %>%
    x = ${2:x_variable},
    y = ${3:y_variable}
    ) + ${4:geom_modifications}
# calling the ggplot snippet
data %>%
x = x_variable,
y = y_variable
) + geom_modifications

As you can see, the coding of the snippets is slightly different than regular R code. Variables are defined using the format {1:variable_name}. The $ indicates where the cursor should jump to when you tab forward (so this should precede all the variables that need to be filled in). For more information about snippets and how to create your own, check out this link: https://support.rstudio.com/hc/en-us/articles/204463668-Code-Snippets. More advanced tips and examples can be found here: https://jozef.io/r906-rstudio-snippets/.

formatting RMarkdown documents

see https://rmarkdown.rstudio.com/authoring_basics.html

This supplement was put together by Risa Gelles-Watnick.