01 / 21
R my_var avg_score

Naming Conventions
in R Programming

Learn how to write clear, readable variable names and avoid accidentally masking built-in R functions: the foundation of clean code.

R Programming

What Are Naming Conventions?

A naming convention is a set of rules for choosing the names you give to variables, functions, and data objects in your code. Good names make your code self-documenting: anyone reading it can understand what each piece does.

Why Naming Matters in R

Readability
You (and others) will re-read your code weeks later. Clear names save hours of confusion.
Debugging
Descriptive names make error messages meaningful. student_avg is easier to trace than x.
Safety
Poor names can accidentally mask built-in functions like mean, sum, or c, breaking your code silently.

R's Naming Rules

Valid R Name Rules Start with a letter or a dot (not a number) Use letters, numbers, dots (.) and underscores (_) Case-sensitive
\( \text{Name} \neq \text{name} \neq \text{NAME} \)
No spaces or special chars No @, #, $, !, -, etc. No reserved words TRUE, FALSE, NULL, if, for... ✓ my_data ✓ score.1 ✕ 2nd_try

Popular Naming Styles in R

Style Example Usage
snake_case student_score Most recommended
dot.case student.score Traditional R style
camelCase studentScore Common in other languages
PascalCase StudentScore Less common in R
ALL_CAPS MAX_SIZE Constants only

What Is Function Masking?

Masking occurs when you create a variable with the same name as a built-in R function. R will use your variable instead of the function, silently breaking your code.

# This MASKS the built-in mean() function! mean <- 42 # Now this will ERROR: mean(c(10, 20, 30)) # Error in mean(...) : attempt to apply non-function

The R Search Path

When you use a name like mean, R searches for it in a specific order of environments. This is called the search path. It always starts with your current workspace, the Global Environment.

1. SEARCHED FIRST Global Environment 2. THEN Loaded Packages 3. FINALLY Base R Packages If mean <- 42 is found here... ...R never reaches here!

Safe vs. Dangerous Names

✓ Safe Names
avg_score <- mean(scores) total_count <- sum(counts) values <- c(1, 2, 3) is_valid <- TRUE df_students <- data.frame(...)
✕ Dangerous Names
mean <- mean(scores) sum <- sum(counts) c <- c(1, 2, 3) T <- TRUE data <- data.frame(...)

Functions to Never Mask

c
The combine function: creates vectors. Most commonly masked name in R.
mean / sum
Core stats functions. Storing results in mean or sum hides them.
T / F
Abbreviations for TRUE/FALSE. They are not reserved: you can overwrite them.
data / df
data() loads datasets. df is the F-distribution function.

How to Fix a Masked Function

1
Detect the problem. You get an error like "could not find function" or unexpected behavior from a built-in function.
2
Remove the masking variable using rm(mean) to delete your variable and restore the original function.
3
Force the base version with base::mean(x) to explicitly call the function from the base package.
4
Rename your variable to something descriptive like avg_score instead of mean.

Naming Checklist

1
Is it descriptive? The name should reveal purpose: student_ages not x.
2
Is it snake_case? Use lowercase words separated by underscores: max_value.
3
Does it start with a letter? Never begin with a number or special character.
4
Does it avoid built-in names? Check that c, mean, sum, data, T, F aren't overwritten.
5
Is it concise but clear? Aim for 2-4 words max. avg_test_score is good; the_average_of_all_test_scores is too long.

Example 1: Basic Naming

Task: Store the ages of five students and calculate their average age.

# Good: descriptive snake_case names student_ages <- c(15, 16, 14, 17, 15) avg_age <- mean(student_ages) cat("Average age:", avg_age) # Average age: 15.4

Example 2: Avoiding Masking

Task: Create a vector of test scores, compute the sum, and then compute the mean.

✕ Broken Version
# Masks c() and sum()! c <- 10 sum <- 85 + 90 # Both lines now FAIL: scores <- c(85, 90, 78) sum(scores)
✓ Fixed Version
# Safe, descriptive names num_classes <- 10 total_score <- 85 + 90 # Now everything works: scores <- c(85, 90, 78) sum(scores)

Example 3: Full Analysis

Task: Load a dataset, filter rows, and compute a summary statistic: all with clean naming.

# Clear, consistent snake_case throughout raw_data <- read.csv("students.csv") # Filter to students who passed (score >= 60) passing_students <- raw_data[raw_data$score >= 60, ] # Calculate passing rate num_total <- nrow(raw_data) num_passing <- nrow(passing_students) pass_rate <- num_passing / num_total cat("Pass rate:", round(pass_rate * 100, 1), "%")

Common Mistakes

✕ Single-Letter Names
Using x, y, a for everything. Fine in short math formulas, but terrible for data analysis scripts.
✕ Masking c() or T/F
Writing c <- 5 or T <- "text". These are the most common silent errors in R.
✕ Inconsistent Style
Mixing myVar, my_var, and my.var in the same script. Pick one style and stick with it.

Summary: Naming Best Practices

Principle Bad Example Good Example
Descriptive x student_count
snake_case MyData my_data
No masking mean <- 5 avg_val <- 5
No reserved words TRUE <- 0 is_valid <- TRUE
Concise the_total_number_of_all_items item_count

Question 1 of 5

Which of the following is a valid R variable name?

Question 2 of 5

What happens if you run c <- 10 and then try to use c(1, 2, 3)?

Question 3 of 5

Which naming style is recommended by the tidyverse style guide for R?

Question 4 of 5

You accidentally ran mean <- 50. How do you restore the original mean() function?

Question 5 of 5

Which of the following variable names is most likely to cause a silent bug in your R code?