R Variable Names
R has specific rules and common conventions for naming variables that keep your code valid and easy to read.
Rules for Valid Names
- Must start with a letter (or a dot not followed by a number)
- Can contain letters, numbers, dots (.), and underscores (_)
- Cannot start with a number
- Cannot contain spaces or symbols like -, +, %, or #
- Cannot be a reserved word such as TRUE, FALSE, if, or function
Example
total_sales <- 500
total.sales <- 500
Sales2024 <- 500
print(total_sales)Invalid Name Examples
Naming Conventions
R allows several naming styles, and consistency matters more than which one you pick. snake_case (total_sales) and dot.case (total.sales) are both common in R code, while camelCase (totalSales) is more familiar to people coming from other languages.
- snake_case — words separated by underscores, e.g. customer_id
- dot.case — words separated by dots, e.g. customer.id
- camelCase — words joined using capital letters, e.g. customerId
Reserved Words
Certain words are reserved by R for its own syntax and cannot be used as variable names, including if, else, for, while, function, TRUE, FALSE, NULL, NA, and Inf. Attempting to assign a value to one of these produces a syntax error.
Example
if_value <- 5 # allowed, "if_value" is not the reserved word "if"
print(if_value)Note: Avoid naming variables the same as common built-in functions, like c, mean, or data — it works, but it silently hides the original function for the rest of your session and can cause confusing bugs.