Variables are the building blocks of data in any programming language. Any object in the R environment exists as a variable with a name - including vectors, lists, data tables, and other objects.

Assigning a value to a variable

Let’s create a variable with the name a:

a <- 5

The <- symbol resembles a left arrow and in R it means “assign the value of the right-hand side to the name on the left-hand side”. So this piece of code assigns the numeric vector 5 to the name a. A single equal sign (=) may also be used instead of <-.

Note: Assigning a value to a name that already exists will overwrite the existing value. This is often desired, but be mindful not to overwrite important variables unintentionally.

Viewing a variable’s content

After it’s assigned, we can call the name of a variable to see its value or use it in calculations:

a
## [1] 5
b <- a + 3

This last piece of code assigns the value of a + 3 (in this case, 8) to b.

Variable names

The name of a variable is meant to signify what it represents. For both the programmer’s and the reader’s sake, the name of a variable should make it easy to understand what it represents.

There are also certain rules that must be followed:

  • Latin alphabet letters, digits, dots and underscores (_) are allowed.

  • A name can contain digits but cannot start with a digit.

  • Names are case-sensitive: a is a different name from A.