01 / 20
R

Style Conventions
in R Programming

Learn to write clean, readable, and consistent R code by following the tidyverse style guide: naming, spacing, indentation, and more.

R Programming

Why Does Code Style Matter?

Code is read far more often than it is written. Consistent style conventions make your R programs easier to understand, debug, and share with collaborators. Style is not about personal preference: it is about communication.

The Tidyverse Style Guide

The tidyverse style guide is the most widely adopted set of conventions for writing R code. Created by Hadley Wickham, it covers everything from how you name variables to how you indent your pipes.

Naming
How to name variables, functions, and files
Spacing
Where to place spaces around operators and commas
Structure
Indentation, line length, and code organization

Anatomy of Well-Styled Code

# Calculate average score per student avg_score <- student_data |> group_by ( student_id ) |> summarise ( avg = mean ( score )) snake_case naming spaces around <- consistent indentation comment

Core Rule: snake_case Naming

The tidyverse style guide mandates snake_case for all object names: variables, functions, and arguments. Words are separated by underscores and everything is lowercase.

✓ Correct day_one
student_count
calc_mean_score
is_valid
✕ Avoid DayOne (CamelCase)
dayone (no separator)
day.one (dots)
day1 (ambiguous)

Core Rule: Spacing Around Operators

Always place spaces around operators like <-, =, +, -, ==, and after every comma. This makes expressions easier to scan visually.

✓ Correct x <- 5
total <- a + b
mean(x, na.rm = TRUE)
✕ Avoid x<-5
total<-a+b
mean(x,na.rm=TRUE)

<- vs =: Assignment Style

Both <- and = can assign values in R, but they have different conventions and subtle differences in behavior.

<- (arrow) = (equals)
Convention Tidyverse standard Less common for assignment
Global Assignment ✓ Works everywhere ✓ Works everywhere
Inside function() Assigns variable in current scope Sets argument only
Readability Clear intent Can confuse with ==
Keyboard shortcut Alt + - (RStudio) n/a

Indentation & Line Length

1
Use 2 spaces for indentation. Never use tabs. Configure your editor to insert spaces when you press Tab.
2
Limit lines to 80 characters. If a line is too long, break it after a comma or a pipe operator.
3
Indent continued lines by 2 more spaces. Each additional level of nesting gets 2 more spaces.
4
Place the pipe |> at end of line, not the beginning. The next line starts indented.
# Good: pipe at end, indented continuation
result <- data |>
  filter(age > 18) |>
  select(name, score) |>
  arrange(desc(score))

How to Apply Style Conventions

1
Choose snake_case for all names. Variables, functions, file names: my_data.R, calc_total(), max_value.
2
Add spaces around every operator. Write x <- 10 not x<-10. Space after commas: c(1, 2, 3).
3
Set RStudio to 2-space indent. Go to Tools > Global Options > Code > set "Tab width" to 2 and check "Insert spaces for Tab."
4
Break long lines at 80 characters. Use the margin guide in RStudio (a thin vertical line at column 80).
5
Run styler::style_file(). The styler package auto-formats your code to tidyverse conventions.

Example 1: Fixing Names

A student wrote the following code. Let's restyle it following the tidyverse guide.

✕ Before myData <- read.csv("file.csv")
Total.Count <- nrow(myData)
avgScore <- mean(myData$Score)
✓ After my_data <- read_csv("file.csv")
total_count <- nrow(my_data)
avg_score <- mean(my_data$score)

Example 2: Spacing & Pipes

This code runs correctly but violates several spacing and structure rules.

✕ Before result<-data%>%filter(age>18)%>%select(name,score)%>%arrange(desc(score))
✓ After result <- data |>
  filter(age > 18) |>
  select(name, score) |>
  arrange(desc(score))

Example 3: Function Definitions

Functions deserve special care. Name them as verbs, document their purpose, and format the body consistently.

✕ Before f=function(x,y){
x+y/2}
✓ After # Calculate midpoint of two values
calc_midpoint <- function(x, y) {
  (x + y) / 2
}

Writing Good Comments

1
Start with # followed by a single space. Write # Load data not #Load data or # Load data.
2
Explain why, not what. The code itself shows what happens. Comments explain the reasoning behind a decision.
3
Use section headers to organize. RStudio recognizes # Section Name ---- (with four or more dashes) as collapsible sections.
# Load packages ----
library(tidyverse)

# Import data ----
# Using read_csv for automatic type detection
raw_data <- read_csv("survey_results.csv")

File Naming & Organization

File names follow the same snake_case rules as variable names, with a few extra conventions for projects.

✓ Good Names
01_import_data.R
02_clean_data.R
03_analysis.R
utils_plotting.R
✕ Bad Names
finalFINAL2.R
stuff.R
my script (1).R
Code.R

Common Mistakes

✕ Inconsistent Naming
Mixing camelCase, dots, and snake_case in the same script. Pick one style and stick with it.
✕ No Spaces
Writing x<-y+z instead of x <- y + z. Cramped code is much harder to scan and debug.
✕ Overly Long Lines
Putting an entire pipeline on one line. Breaks readability and makes version control diffs messy.
✕ Cryptic Names
Using x, d2, or tmp for important variables. Future you will not remember what they mean.

Style Cheat Sheet

Convention Do Don't
Variable names snake_case camelCase, dot.case
Assignment <- =
Spacing x <- y + z x<-y+z
Indentation 2 spaces tabs or 4 spaces
Line length < 80 characters unlimited
Pipe placement end of line start of line
Comments # space then text #no space
File names 01_clean_data.R Clean Data.R

Question 1 of 5

Which of the following variable names follows the tidyverse style guide?

Question 2 of 5

What is the recommended assignment operator in the tidyverse style guide?

Question 3 of 5

How many style violations does this single line contain?

Question 4 of 5

What is the recommended indentation size in the tidyverse style guide?

Question 5 of 5

Which comment style follows tidyverse conventions?