Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
What are vectors?
Vector operations
11. Arithmetic with vectors of different sizes
Indexing and filtering


Good job! Be careful when working with vectors that are not of the same size as you will get unexpected results.

When you try to sum two vectors of different lengths, R responds by stretching the smaller vector so it matches the length of the longer vector. It does this by recycling each element from the start of the smaller vector, one by one, and appending them to its end. For example, suppose we try to sum the following two vectors:

c(1, 2, 3, 4, 5) + c(10, 20)

Under the hood, R will treat the second vector as c(10, 20, 10, 20, 10). The result of adding the two vectors will thus be:

[1] 11 22 13 24 15

Note that this is also how operations with single-value vectors work.

In other words, when we add a single value to a vector, such as

c(1, 2, 3, 4, 5) + 5

R takes the single element (which in reality is treated as a vector) and recycles its elements (in this case, there's only one element) until it matches the length of the other vector.


By mistake, someone tried to apply the Department 1 multipliers to Department 2 salaries. These two vectors are not of the same length. Run the template code. Observe that R issues a warning.