An R Introduction to Statistics

Vector Arithmetics

Arithmetic operations of vectors are performed member-by-member, i.e., memberwise.

For example, suppose we have two vectors a and b.

> a = c(1, 3, 5, 7) 
> b = c(1, 2, 4, 8)

Then, if we multiply a by 5, we would get a vector with each of its members multiplied by 5.

> 5 * a 
[1]  5 15 25 35

And if we add a and b together, the sum would be a vector whose members are the sum of the corresponding members from a and b.

> a + b 
[1]  2  5  9 15

Similarly for subtraction, multiplication and division, we get new vectors via memberwise operations.

> a - b 
[1]  0  1  1 -
 
> a * b 
[1]  1  6 20 56 
 
> a / b 
[1] 1.000 1.500 1.250 0.875

Recycling Rule

If two vectors are of unequal length, the shorter one will be recycled in order to match the longer vector. For example, the following vectors u and v have different lengths, and their sum is computed by recycling values of the shorter vector u.

> u = c(10, 20, 30) 
> v = c(1, 2, 3, 4, 5, 6, 7, 8, 9) 
> u + v 
[1] 11 22 33 14 25 36 17 28 39