Variables and Assignments

We can store values in variables using the assignment operator <-, like this:

x <- 1/40

Notice that the assignment does not print a value. Instead, we stored it for later in something called a variable. x now contains the value 0.025:

x

Output
[1] 0.025


More precisely, the stored value is a decimal approximation of this fraction called a floating point number.

Look for the Environment tab in the top right panel of RStudio, and you will see that x its value has appeared. Our variable x can be used in place of a number in any calculation that expects a number:

log(x)

Output
[1] -3.688879

Notice also that variables can be reassigned:

x <- 100

x is used to contain the value 0.025, and now it has the value 100.

Assignment values can contain the variable being assigned to:

x <- x + 1 #notice how RStudio updates its description of x on the top right tab
 y <- x * 2

The right-hand side of the assignment can be any valid R expression. The right-hand side is fully evaluated before the assignment occurs.

Variable names can contain letters, numbers, underscores, and periods but no spaces. They must start with a letter or a period followed by a letter (they cannot start with a number or an underscore). Variables beginning with a period are hidden variables. Different people use different conventions for long variable names, these include

  • periods.between.words
  • underscores_between_words
  • camelCaseToSeparateWords

What you use is up to you, but be consistent.

It is also possible to use the = operator for assignment:

x = 1/40

But this is much less common among R users. The most important thing is to be consistent with the operator you use. There are occasional places where it is less confusing to use <- than =, and it is the most common symbol used in the community. So the recommendation is to use <-.