๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

R Vector Math

Vector math is arithmetic that works on a whole vector at once. Each item pairs with the item at the same position in the other vector.

Adding and subtracting pairs

Two vectors pair up item by item. The first print adds each pair and the second print subtracts each pair.

a <- c(10, 20, 30)
b <- c(1, 2, 3)
print(a + b)
print(a - b)

Multiplying and dividing pairs

The same two vectors pair up again here. The first print multiplies each pair and the second print divides each pair.

a <- c(10, 20, 30)
b <- c(1, 2, 3)
print(a * b)
print(a / b)

One number against a vector

One number pairs with every item in the vector. The first print doubles each item and the second print squares each item.

v <- c(3, 5, 7)
print(v * 2)
print(v ^ 2)

Recycling a shorter vector

The shorter vector repeats from its start. Its two values pair with the four values in turn.

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

Example

prices <- c(10, 15, 20)
doubled <- prices * 2
print(doubled)
print(doubled + prices)

Key points

  • Addition, subtraction, multiplication and division all work pair by pair.
  • The two vectors in a calculation are read side by side.
  • A single number pairs with every item in a vector.
  • The power operator raises every item to the same power.
  • When the two lengths differ, the shorter vector repeats from its start.
  • The repeat is called recycling.

In this example, each price is doubled in one step. Adding the first vector back then gives three times each price.

Note

R warns when the longer length is not a multiple of the shorter length.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does c(1, 2, 3, 4) + c(10, 20) print?