1.11 Basic operations

Above you learned how to use R as a calculator. For example, the code 5 + 5 applies the addition operator to two numbers. How do we apply operators to vectors and matrices?

When you apply an arithmetic operator or function to a vector or matrix, it is applied elementwise; that is, it is applied to each element of the vector or matrix and returns a vector or matrix of the same size.

x <- c(0, 2, 4)
x
## [1] 0 2 4
x + 1
## [1] 1 3 5
x - 1
## [1] -1  1  3
x * 2
## [1] 0 4 8
x / 2
## [1] 0 1 2
sqrt(x)
## [1] 0.000 1.414 2.000
x <- matrix(c(0, 2, 4, 6, 8, 10), nrow = 3)
x
##      [,1] [,2]
## [1,]    0    6
## [2,]    2    8
## [3,]    4   10
x + 1
##      [,1] [,2]
## [1,]    1    7
## [2,]    3    9
## [3,]    5   11

If you apply an operation to multiple objects, they have to be the same length (for a vector) or dimension (for a matrix).

x <- c(1, 2, 4)
y <- c(5, 0, 8)
x + y 
## [1]  6  2 12

What happens if you try to add two vectors that are not the same length? R “recycles” the shorter object, but only gives you a warning if the length of one vector is not a multiple of the length of the other.

For example, if you add a vector of length 6 to a vector of length 3, the length 3 vector is turned into a length 6 vector first by repeating its values before the addition.

x <- c(1, 2, 4, 5, 3, 1)
y <- c(1, 0, 1)
x + y
## [1] 2 2 5 6 3 2

Since 6 is a multiple of 3, there was no warning.

In the example below, where the length of one vector is not a multiple of the other, you will get a warning. R “recycles” just enough elements to make the two vectors match in length. when R got to the 4th element of x and saw that y had run out of elements, it went back to the beginning of y and added the 1st element of y to the 4th element of x, but with a warning.

x <- c(5, 0, 8, 3)
y <- c(1, 2, 4)
x + y
## Warning in x + y: longer object length is not a multiple of shorter object length
## [1]  6  2 12  4

NOTE: It is not good practice to rely on R’s default recycling feature, even if it produces the result you want. Better to only operate on objects of the same length. While it does produce a warning in some situations, if one object’s length is a multiple of the other, you would not even get a warning!