How to Store and Calculate Values in R

By Andrie de Vries, Joris Meys

Using R as a calculator is very interesting but perhaps not all that useful. A much more useful capability is storing values and then doing calculations on these stored values.

Try the following:

> x <- 1:5
> x
[1] 1 2 3 4 5

In these two lines of code, you first assign the sequence 1:5 to a variable called x. Then you ask R to print the value of x by typing x in the console and pressing Enter.

In R, the assignment operator is <-, which you type in the console by using two keystrokes: the less-than symbol (<) followed by a hyphen (). The combination of these two symbols represents assignment.

In addition to retrieving the value of a variable, you can do calculations on that value. Create a second variable called y, and assign it the value 10. Then add the values of x and y, as follows:

> y <- 10
> x + y
[1] 11 12 13 14 15

The values of the two variables themselves don’t change unless you assign a new value. You can check this by typing the following:

> x
[1] 1 2 3 4 5
> y
[1] 10

Now create a new variable z, assign it the value of x+y, and print its value:

> z <- x + y
> z
[1] 11 12 13 14 15

Variables also can take on text values. You can assign the value “Hello” to a variable called h, for example, by presenting the text to R inside quotation marks, like this:

> h <- "Hello"
> h
[1] "Hello"

You must present text or character values to R inside quotation marks — either single or double. R accepts both. So both h <- “Hello” and h <- ‘Hello’ are examples of valid R syntax.

In “Using vectors,” you use the c() function to combine numeric values into vectors. This technique also works for text. Try it:

> hw <- c("Hello", "world!")
> hw
[1] "Hello" "world!"

You can use the paste() function to concatenate multiple text elements. By default, paste() puts a space between the different elements, like this:

> paste("Hello", "world!")
[1] "Hello world!"