R Variable Names (Identifiers)

🏷️ R Variable Names (Identifiers)

In R, variable names are also called identifiers.

They are used to identify variables, functions, and objects in a program.


🔹 1. Rules for R Variable Names

✔ Must start with a letter (a–z / A–Z) or a dot (.)
✔ Can contain letters, numbers, dots (.), and underscores (_)
❌ Must not start with a number
❌ Must not be a reserved keyword

✅ Valid Variable Names

age <- 25
.total <- 100
student_name <- "Rahul"
marks1 <- 85

❌ Invalid Variable Names

1age <- 20 # starts with number
student-name <- "A" # hyphen not allowed
if <- 10 # reserved keyword

🔹 2. Case Sensitivity

R is case-sensitive, so these are different:

score <- 90
Score <- 95

🔹 3. Reserved Keywords in R

These words cannot be used as variable names:

if, else, repeat, while, function,
TRUE, FALSE, NULL, NA, Inf, NaN


🔹 4. Using Dot (.) in Variable Names

student.marks <- 88

✔ Valid
⚠ Avoid starting with ., as some system variables use it.


🔹 5. Using Underscore (_) in Variable Names

total_marks <- 450

✔ Preferred naming style
✔ Improves readability


🔹 6. Length of Variable Names

  • No fixed limit, but keep names short and meaningful

  • Avoid very long names

❌ Bad:

x <- 10

✅ Good:

total_price <- 10

🔹 7. Best Naming Conventions (Recommended)

✔ Use lowercase letters
✔ Use underscore (_) between words
✔ Choose meaningful names

Examples:

student_age <- 20
total_salary <- 50000
is_passed <- TRUE

🔹 8. Check if a Name is Valid

make.names("student-name")

Output:

[1] "student.name"

📌 Summary

  • Variable names are called identifiers

  • Must start with letter or dot

  • No spaces or special symbols

  • Case-sensitive

  • Follow good naming conventions for clean code

You may also like...