01 / 21
R

Naming &
Formatting

Learn to write clean, readable R code by choosing meaningful variable names and following consistent formatting conventions.

R Programming

Why Does Naming Matter?

Code is read far more often than it is written. When you revisit your R script six months later, or share it with a classmate, the names you choose determine whether the code is instantly understandable or a confusing puzzle.

✓ Readable
Other people (and future you) can understand your code quickly.
✓ Debuggable
Meaningful names help you spot logic errors much faster.
✓ Collaborative
Teams rely on consistent style to work on the same codebase.

What Is a Variable Name?

In R, a variable name (also called an identifier) is the label you assign to a stored value using the assignment operator <-. The name is how you refer to that value later in your script.

# Variable name = "student_count" student_count <- 35 # Variable name = "avg_score" avg_score <- mean(test_scores)

What Is Code Formatting?

Formatting refers to the visual layout of your code: how you use whitespace, indentation, line breaks, and alignment to make your script easy to scan and understand.

Messy x<-c(1,2,3,4,5) y=mean(x) if(y>3){print("hi")} z <- x+y ✕ No spacing consistency ✕ Mixed assignment style ✕ No indentation ✕ Single-letter names Clean scores <- c(1, 2, 3, 4, 5) avg_score <- mean(scores) if (avg_score > 3) { print("Above average") } ✓ Spaces around operators ✓ Consistent <- assignment ✓ Proper indentation ✓ Descriptive names

The Golden Rule of Naming

✕ Bad names
x <- 98.6 temp <- read.csv("data.csv") d <- Sys.Date() val2 <- 100
✓ Good names
body_temp_f <- 98.6 survey_data <- read.csv("data.csv") today <- Sys.Date() max_retries <- 100

R Naming Conventions

R programmers use several conventions. The tidyverse style guide recommends snake_case as the standard for variable and function names.

snake_case student_grade_avg ★ Recommended camelCase studentGradeAvg Common in legacy R dot.case student.grade.avg Avoid: conflicts with S3 SCREAMING_SNAKE_CASE: for constants only (MAX_RETRIES)

snake_case vs camelCase

snake_case camelCase
Word separator Underscore ( _ ) Capital letter
Example total_sales totalSales
Tidyverse standard ✓ Yes ✕ No
Readability Higher (underscores act as spaces) Good, but harder to scan
Used in base R Some functions Some functions
Best for New R projects Matching existing codebase

Core Formatting Rules

1
Use <- for assignment, not = (which is ambiguous inside function calls).
2
Spaces around operators: write x <- 5, not x<-5. Same for +, -, *, /, ==, etc.
3
Space after commas: write c(1, 2, 3), not c(1,2,3).
4
Indent with 2 spaces (not tabs). Each nesting level adds 2 more.
5
Keep lines under 80 characters. Break long expressions across multiple lines.

Indentation & Braces

Proper indentation shows the logical structure of your code. In R, the opening brace { goes on the same line as the control statement, and the closing brace } gets its own line.

calculate_grade <- function(score) { if (score >= 90) { grade <- "A" } else if (score >= 80) { grade <- "B" } else { grade <- "C" } return(grade) }

How to Apply These Rules

1
Pick snake_case and commit to it for all variable and function names in your project.
2
Name the "what," not the "how": use avg_temperature instead of result or calc_val.
3
Add spaces around every <-, +, ==, and after every comma.
4
Indent consistently with 2 spaces for each nesting level inside {}.
5
Use the styler package: run styler::style_file("my_script.R") to auto-format your code.

Example 1: Basic Naming

A student writes a script to calculate the average of quiz scores. Let's improve the variable names.

✕ Before
a <- c(85, 92, 78, 95, 88) b <- mean(a) c <- max(a) print(b) print(c)
✓ After
quiz_scores <- c(85, 92, 78, 95, 88) avg_score <- mean(quiz_scores) top_score <- max(quiz_scores) print(avg_score) print(top_score)

Example 2: Formatting a Function

This function reads a CSV file and filters rows. Watch how spacing and indentation transform the readability.

✕ Before
f=function(fn,t){ d=read.csv(fn) d=d[d$age>t,] return(d)}
✓ After
filter_by_age <- function(file_path, min_age) { raw_data <- read.csv(file_path) filtered <- raw_data[raw_data$age > min_age, ] return(filtered) }

Example 3: A Complete Script

Putting it all together: a well-formatted R script that loads data, processes it, and outputs results.

# Load and summarize student performance data student_data <- read.csv("students.csv") # Calculate summary statistics num_students <- nrow(student_data) avg_gpa <- mean(student_data$gpa, na.rm = TRUE) # Flag students on honor roll honor_roll <- student_data[student_data$gpa >= 3.5, ] # Report results cat("Total students:", num_students, "\n") cat("Average GPA:", round(avg_gpa, 2), "\n") cat("Honor roll count:", nrow(honor_roll), "\n")

Comments & Documentation

Good names reduce the need for comments, but comments still have an important role: they explain why, not what.

✕ Useless comment
# Set x to 10 x <- 10
✓ Useful comment
# FDA threshold for safe lead level (ppb) safe_lead_limit <- 10
Explain why
Why did you choose this threshold? Why filter here?
Not what
The code already shows "what." Don't repeat it in English.

Common Mistakes

✕ Single-letter names
Using x, d, or n instead of descriptive names. Only acceptable in tiny math formulas like for (i in 1:n).
✕ Mixing conventions
Using student_count on one line and avgScore on the next. Pick one style and stick with it.
✕ No spaces
Writing x<-5+y*2 instead of x <- 5 + y * 2. Missing spaces make code much harder to read.
✕ Shadowing built-ins
Naming a variable c, t, data, or list. These override R's built-in functions and cause silent bugs.

Quick Reference Table

Rule Bad Good
Variable names x, d2, myVal avg_score, total_count
Assignment x = 5 x <- 5
Operator spacing y<-x+1 y <- x + 1
Comma spacing c(1,2,3) c(1, 2, 3)
Indentation Tabs / 4 spaces 2 spaces per level
Line length > 120 characters < 80 characters
Comments # set x to 5 # FDA max limit (ppb)

Question 1 of 5

Which variable name follows the tidyverse snake_case convention?

Question 2 of 5

What is wrong with using c as a variable name in R?

Question 3 of 5

Which line of R code has correct formatting according to the tidyverse style guide?

Question 4 of 5

A classmate writes: d <- read.csv("survey.csv"). Which rename is the best improvement?

Question 5 of 5

What is the recommended indentation style in R according to the tidyverse guide?