Chapter 4 Naming variables

You might have noticed so far that I’ve used very simple letters or names for my variables, and that they have all been written in lower case. R does have more flexibility in what you can name your variables, but it also has some rules…

  • Variable names cannot include spaces: my revenue is not a valid name, but my_revenue is
  • Variable names are case sensitive: Revenue and revenue are different names
  • Variable names must be started with a letter or a full stop: You couldn’t use something like 1revenue or _revenue
  • There are some reserved keywords that cannot be used to name variables with: These include, if, else, for, in, next, TRUE, FALSE, NULL, NA, NaN, repeat, function, NA_integer_, NA_real_, NA_complex_. Don’t worry about remembering these, R will tell you if you make the mistake of trying to name a variable after one of these.

There are a few other things you’d want to consider too, such as using meaningful names, using short names, and using a conventional style for multiword names when necessary. Consistency is key!