6.1 Arithmetic operations on vectors

So far, you know how to do basic arithmetic operations like + (addition), - (subtraction), and * (multiplication) on scalars. Thankfully, R makes it just as easy to do arithmetic operations on numeric vectors:

a <- c(1, 2, 3, 4, 5)
b <- c(10, 20, 30, 40, 50)

a + 100
## [1] 101 102 103 104 105
a + b
## [1] 11 22 33 44 55
(a + b) / 10
## [1] 1.1 2.2 3.3 4.4 5.5

If you do an operation on a vector with a scalar, R will apply the scalar to each element in the vector. For example, if you have a vector and want to add 10 to each element in the vector, just add the vector and scalar objects. Let’s create a vector with the integers from 1 to 10, and add then add 100 to each element:

# Take the integers from 1 to 10, then add 100 to each
1:10 + 100
##  [1] 101 102 103 104 105 106 107 108 109 110

As you can see, the result is [1 + 100, 2 + 100, … 10 + 100]. Of course, we could have made this vector with the a:b function like this: 101:110, but you get the idea.

Of course, this doesn’t only work with addition…oh no. Let’s try division, multiplication, and exponents. Let’s create a vector a with the integers from 1 to 10 and then change it up:

a <- 1:10
a / 100
##  [1] 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10
a ^ 2
##  [1]   1   4   9  16  25  36  49  64  81 100

Again, if you perform an algebraic operation on a vector with a scalar, R will just apply the operation to every element in the vector.

6.1.1 Basic math with multiple vectors

What if you want to do some operation on two vectors of the same length? Easy. Just apply the operation to both vectors. R will then combine them element–by–element. For example, if you add the vector [1, 2, 3, 4, 5] to the vector [5, 4, 3, 2, 1], the resulting vector will have the values [1 + 5, 2 + 4, 3 + 3, 4 + 2, 5 + 1] = [6, 6, 6, 6, 6]:

c(1, 2, 3, 4, 5) + c(5, 4, 3, 2, 1)
## [1] 6 6 6 6 6

Let’s create two vectors a and b where each vector contains the integers from 1 to 5. We’ll then create two new vectors ab.sum, the sum of the two vectors and ab.diff, the difference of the two vectors, and ab.prod, the product of the two vectors:

a <- 1:5
b <- 1:5

ab.sum <- a + b
ab.diff <- a - b
ab.prod <- a * b

ab.sum
## [1]  2  4  6  8 10
ab.diff
## [1] 0 0 0 0 0
ab.prod
## [1]  1  4  9 16 25

6.1.2 Ex: Pirate Bake Sale

Let’s say you had a bake sale on your ship where 5 pirates sold both pies and cookies. You could record the total number of pies and cookies sold in two vectors:

pies <- c(3, 6, 2, 10, 4)
cookies <- c(70, 40, 40, 200, 60)

Now, let’s say you want to know how many total items each pirate sold. You can do this by just adding the two vectors:

total.sold <- pies + cookies
total.sold
## [1]  73  46  42 210  64

Crazy.