Vector Arithmetic


Let's go back to a vector from the previous page.

> x <- c(1.2, 2.3, 0.2, 1.1)

This vector consists of four numbers. In some circumstances, we may want to apply certain operations or calculations to each element in the vector. For example, suppose we wanted to use the vector x to create a new vector "y" with elements that are 2 time each x plus 3. One could do this element by element with the following command:

> y <- c(2*x[1]+3, 2*x[2]+3, 2*x[3]+3, 2*x[4]+3) which gives

[1] 5.4 7.6 3.4 5.2

but a simpler way to do this is to use the command:

> y- 2*x+3

Then if we enter

> y

We get back:

[1] 5.4 7.6 3.4 5.2

 

Logical operators can also be used to modify or select subsets of a data set. For example, in the previous example, we saw that x[c(2,3,4)], x[-1] and x[2:4] work exactly the same and select the last three elements of the vector x.

You can also use

 > x[c(FALSE, TRUE, TRUE)]

This instructs R to skip the first element and then select the next two, so it returns the following:

[1] 2.3 0.2

 

If we wanted to select the elements with values greater than 1, we could use the command: 

> x[x>1]

[1] 1.2 2.3

 

In summary, R can perform functions over entire vectors and can be used to select certain elements within a vector. In addition to the elementary arithmetic operations, R can also use the vector functions listed below.

Create the vector x as follows:

> x <- c(1.2, 2.3, 0.2, 1.1)

 

Then evaluate each of the vector functions listed above.