6.2 Variables

There’s a problem with just entering numbers at the prompt like we have been doing so far. We type in our nice calculation (which we call an expression in programming jargon):

> 5 + 6 / 4 * 5

hit enter, and get the following answer

[1] 12.5

But what if we need this for a subsequent expression? Alas, the answer has disappeared into the ether, because we haven’t saved it anywhere.

To save the result of an expression, we can assign it to a variable. In R, we do this using a left-pointing arrow:

> a <- 5 + 6 / 4 * 5

Try running this line and see what happens.

Hmm! The RStudio console no longer returns the result of the expression. However, take a look in the upper right pane of RStudio. You should see that the R environment now contains a variable a with an associated value of 12.5.

So how do we reuse this variable? Simple: just replace one of the numbers in our expression with the variable, e.g.:

> a + 10
[1] 22.5

We could even save the result of this expression into a second variable:

> b <- a + 10

Take a look in the top right tab in RStudio (called Environment). You should see that there are two variables, a and b, with values 12.5 and 22.5 respectively. RStudio keeps track of all the variables that have been created, along with their values, and shows them here so that you can keep track of them more easily.