Question: What are examples of good variable names and bad variables name?

Variable naming is one of the most important aspects of making your code more readable to others. The best variable names allow for somebody else to easily understand what your variables represent. Below, we will take a look at examples of both good and bad variable names.

Data

We will use the palmerpenguins package for this example. Comment out install.packages after successful installment and load the penguins data.

#install.packages("palmerpenguins")
library(palmerpenguins)
## Warning: package 'palmerpenguins' was built under R version 4.1.2
data(penguins)

Looking at variable names in penguins data

Let’s take a look at the variable names with the penguins dataset with the names() function. This will give us the names of all the coloumns presented.

names(penguins)
## [1] "species"           "island"            "bill_length_mm"   
## [4] "bill_depth_mm"     "flipper_length_mm" "body_mass_g"      
## [7] "sex"               "year"

Good Examples

The variable names in this data are fairly good as they are easy to understand without being too wordy. It’s also great that the units are included in the coloumns that use quantitiative measurements. This allows for somebody to easily understand the data presented.

Bad Examples

What if we changed the variable names? For example, what if we changed “island” to “place?” This is not the worst variable name as it still describes a location, but “island” is much more specific and easy to understand. What if we changed “flipper_length_mm” to “flip?” Flip is not descriptive enough as we cannot easily determine what data the variable contains.

Additional Readings

For more information on this topic, see http://adv-r.had.co.nz/Style.html

Keywords

  1. variables
  2. naming conventions
  3. names()
  4. code readability