Variable Names

Variable names in R must follow certain rules. They should be descriptive and follow best practices to make your code readable and maintainable.

Naming Rules and Best Practices

  • Variable names must start with a letter and can contain letters, numbers, underscores, and periods.
  • They cannot start with a number or contain spaces.
  • R is case-sensitive, so variable and Variable are treated as different names.

Examples of Valid and Invalid Names

# Valid variable names
my_variable <- 10
variable.name <- "R Programming"

Output:

[1] 10
[1] "R Programming"
# Invalid variable names
2ndVariable <- 20 # Cannot start with a number
var name <- 30    # Cannot contain spaces

Output:

Error: unexpected symbol in "var name"

Code Explanation: my_variable and variable.name are valid names, while 2ndVariable and var name are invalid because they break R's naming rules.

Key Takeaways

  • Choose descriptive and meaningful variable names.
  • Follow R's naming rules to avoid errors in your code.
  • Remember that R is case-sensitive when naming variables.