-
Notifications
You must be signed in to change notification settings - Fork 1
Code Style
Brendan Casey edited this page Sep 20, 2025
·
1 revision
Style R code according to the conventions outlined in the tidyverse style guide. Google's R style guide is based in this. While you are encouraged to familiarize yourself with the tidyverse guide, here are some highlights:
Give your files meaningful names and avoid special characters. Use a consistent naming convention:
-
snake_case:
- Words are separated by underscores (
_). - Letters are lowercase.
- Example:
1_your_code_name.R.
- Words are separated by underscores (
-
kebab-case:
- Words are separated by hyphens (
-). - Letters are lowercase.
- Example:
1-your-code-name.R.
- Words are separated by hyphens (
-
camelCase:
- The first word is lowercase, and subsequent words start with a capital letter.
- No spaces or special characters between words.
- Example:
1YourCodeName.R.
Prefix files with numbers to show the order that files should be run:
00_process_response_data.R
01_process_predictor_data.R
...
09_generalized_linear_mixed_models.R
10_visualize_results.R
Object names within the code should be concise, descriptive, and follow a consistent naming convention:
bird_data <- read.csv("bird_species_data.csv")
pred_var <- read.csv("predictor_variables.csv")- Add spaces after commas
- Place a space after
()in functions. -
{{ }}should have inner spaces - Surround operators (
==,+,-,<-, etc.) with spaces. - For curly brackets
{}, end lines with{and start lines with} - Use
<-to assign object names. - Limit the line width of your code to 80 characters for readability. This will ensure that the code can be printed or displayed without cropping.
- Comment your code to explain its purpose, inputs, outputs, and rationale. Comments should begin with # followed by a space.
R code can be automatically formatted according to the tidyverse style guide using the styler R package:
library(styler)
styler::style_file("file/path/file.R", style = tidyverse_style)See the styler documentation for instructions on how to integrate styler into the RStudio GUI.