Owning Outlines in RStudio

December 25, 2019 - 3 minutes
Take advantage of organizing your R scripts in RStudio with these outline tips and tricks.
RStudio productivity

I find myself using RStudio’s outline tool a lot. It’s a great way to keep your code organized and literate, plus it makes navigating larger scripts so much easier! This post is everything I do to get the most out of the outline format.

See the outline

Be the outline. RStudio doens’t start with the outline shown by default (I really wish it did) so you have to open it each time, but it’s easy.

Press the grey button in the upper right of the editor pan with 5 offset dark-grey lines to show/hide the outline. You can also toggle the outline with the keyboard shortcut:

Control+ Shift+ O

Label sections

Like really, just do it. RStudio makes adding section labels super simple, so you don’t have a good excuse not too. To insert a new label you can use helper via the keyboard short cut:

Control+Shift+R

Alternatively, you can type 4 (or more) hypens or pounds at the end of a comment to make it a section label.

# 1 Import ----------------------------------------------------------------
# ^^^ Rstudio's helper pads with hyphens to col 76

# 2 Clean ----
# ^^^ Or you can type 4-hyphens yourself

# Plot ####
# ^^^ Or 4-pounds, but please don't

Label sub-sections

This part is not natively supported by RStudio’s outline, but I think it’s a super useful hack and easy enough to do that I still reccomend it.

I’ll denote a sub-section by prepending a section label with * (note there should be a trailing space). This works well for extending further into sub-sub-sections and I think it renders cleanly in the outline pane too.

# 1 Import ----------------------------------------------------------------

# * 1.1 Databases ---------------------------------------------------------

# * * 1.1.1 Postgres ------------------------------------------------------

Label functions

Functions self-label, so you just consider the section you want to define them in. Whenever you write a new function, it will add itself as a child to the section label above it in the outline. If a function has internal functions, those will added as children of the top-level function.

Fold labels

Sometimes it can be helpful to fold or hide code while you work on another section. Any section that appears in the ouline can be collapsed by clicking the dark-grey down arrow at the starting line in the row index area on the right of the editor pane.

And of course there is a keyboard shortcut to accomplish the same:

Cmd+ Alt+ L

Unfold labels

Clicking the now horizontal arrow in the row index area with unfurl folded sections. The keyboard short is the same as above but with Shift added:

Cmd+ Alt+ Shift+ L

Example outline

I mocked up a small example .r file to show all of these together. Just open in RStudio to explore and I hope you enjoy the perks of outlining your Rscripts!