3. Simple arithmetical operations involving vectors


Now that you have stored values or data elements in vectors, you may start working with/on these vectors. The simplest operations that you can perform are regular arithmetical operations such as addition, subtraction, multiplication and division. Here is an example where the vector data1 is multiplied by 5:

[code language=”r”]
data1 = c(1,2,3,4,5)
data1

data1 * 5
[/code]

simple ops vectors

 

 

 

 

 

 

 

 

 

As you see in the picture above, each of the data elements in data1 has been multiplied by 5. This will also happen when adding, subtracting and dividing.

Now, see what happens when we add a vector to another one of the same length (meaning that both vectors contain an equal amount of elements):

[code language=”r”]
data1 = c(1,2,3,4,5)
data2 = c(10,20,30,40,50)

data1 + data2
[/code]

add vectors

 

 

 

 

 

 

 

 

R takes the first element of each vector and adds them, then does the same with the second element, the the third, until the end is reached.

But then, what happens when one of the vectors is shorter than the other:

[code language=”r”]
data1 = c(1,2,3,4,5,6)
data2 = c(10,20)

data1 * data2
[/code]

multiply vectors

 

 

 

 

 

 

 

 

 

As seen before, R takes the first element of each vector and multiplies them, then the second elements are multiplied. For the next operation, R picks up the third element of the longest vector and picks up the first value of the shorter vector again since the shorter vector ran out of values. This is called recycling. R has indeed recycled the shorter vector twice to perform operations on ALL the data elements of the longest vector.

In the present example, it happens that the number of elements in the longer vector (6) is a multiple of the number of elements (2) in the shorter vector. The recycling has been complete. But what happens if the longer vector is NOT a multiple of the shorter:

[code language=”r”]
data1 = c(1,2,3,4,5)
data2 = c(10,20)

data1 * data2
[/code]

multiply vectors size

The operations have been performed as expected. However, since the end of the longer vector was reached before the shorter vector was completely recycled, R fell obliged to let you know about the situation with a friendly warning.

One last example to see what happens when we perform an arithmetic operation on a vector containing words (text):

[code language=”r”]
data1 = c("aa","bb","cc","dd","ee")
data1 + 1
[/code]

operation text vector

An error message pops up and tells you that this type of operation is impossible due to the different types of data elements.

  Fant du det du lette etter? Did you find this helpful?
[Average: 0]