Basic Operations in R

Let’s get started using R. When you enter an expression into the R console and press the Enter key, R will evaluate that expression and display the results (if there are any). If the statement results in a value, R will print that value. For example, you can use R to do simple math:

> 1 + 2 + 3
[1] 6
> 1 + 2 * 3
[1] 7
> (1 + 2) * 3
[1] 9

The interactive R interpreter will automatically print an object returned by an expression entered into the R console. Notice the funny “[1]” that accompanies each returned value. In R, any number that you enter in the console is interpreted as a vector. A vector is an ordered collection of numbers. The “[1]” means that the index of the first item displayed in the row is 1. In each of these cases, there is also only one element in the vector.

You can construct longer vectors using the c(...) function. (c stands for “combine.”) For example:

> c(0, 1, 1, 2, 3, 5, 8)
[1] 0 1 1 2 3 5 8

is a vector that contains the first seven elements of the Fibonacci sequence. As an example of a vector that spans multiple lines, let’s use the sequence operator to produce a vector with every integer between 1 and 50:

> 1:50
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22
[23] 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
[45] 45 46 47 48 49 50

Notice the numbers in the brackets on the lefthand side of the results. These indicate the index of the first element shown in each row.

When you perform an operation on two vectors, ...

Get R in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.