# First code section ----
<- 1
a
# Second code section ----
<- 2
b
# Third code section ----
<- 3 c
Introduction
The admiral
package embraces a modular style of programming, where blocks of code are pieced together in sequence to create an ADaM dataset. However, with the well-documented advantages of the modular approach comes the recognition that scripts will on average be longer. As such, astute programmers working in RStudio are constantly on the lookout for quick ways to effectively navigate their scripts. Enter code sections!
So, what are code sections and why are they useful?
Code Sections are separators for long R scripts or functions in RStudio. They can be set up by inserting a comment line followed by four or more dashes in between portions of code, like so:
RStudio then recognizes the code sections automatically, and enables you to:
- Collapse and expand them using the arrow displayed next to the line number, or with the handy shortcuts
Alt+L
/Shift+Alt+L
on Windows orCmd+Option+L
/Cmd+Shift+Option+L
on Mac. - Travel in between them using the navigator at the bottom of the code pane, or by pressing
Shift+Alt+J
on Windows orCmd+Shift+Option+J
on Mac. - View an outline of the file using the “Outline” button at the top right of the pane and/or the orange hashtag “Section Navigator” button at the bottom left of the pane.
It is also possible to create subsections by using two hashtags at the start of a comment line:
# First code section ----
<- 1
a
## A code subsection ----
<- 2
b
# Second code section ----
<- 3 c
For a complete list of Code Sections shortcuts, and for further information, see here.
Code Sections on admiral
Within the admiral
package, heavy use of code sections is made in scripts such as our template ADaM programs. This ensures that they are more traversable and also encourages good commenting practices throughout the program. Here is an example using the ADAE template program:
library(admiral)
use_ad_template("ADAE")
Once the user saves this template program and opens it in their local file system, a 100+ line file instantly becomes more tractable due to the code sections that have been inserted.
Conclusion
Code sections are an easy way to navigate long scripts and foster good commenting practices. They are used extensively in the admiral
package, but there is no reason that you cannot start using them yourself in your day-to-day R programming!
Last updated
2024-12-13 13:35:49.706479
Details
Reuse
Citation
@online{mancini2023,
author = {Mancini, Edoardo},
title = {How to Use {Code} {Sections}},
date = {2023-07-14},
url = {https://pharmaverse.github.io/blog/posts/2023-07-14_code_sections/code_sections.html},
langid = {en}
}