How to Use the Vector Math in R

Vector math in R can be “used to perform mathematical operations on vectors”.

Example 1: Vector arithmetics

Let’s define two vectors and perform the addition operation.

vcA <- c(11, 21, 19)
vcB <- c(6, 18, 46)

summation <- vcA + vcB
cat(summation)

Output

17 39 65

The output here is the vector, the sum of the corresponding elements of two vectors, vcA and vcB.

Example 2: Subtraction in R Vector

We can perform the subtraction the same way as the vector addition.

vcA <- c(11, 21, 19)
vcB <- c(6, 18, 46)

subtract <- vcA - vcB
cat(subtract)

Output

5 3 -27

Example 3: Division in R Vector

To perform a division operation in an R vector, use the following code.

vcA <- c(10, 20, 30)
vcB <- c(2, 4, 6)

subtract <- vcA / vcB
cat(subtract)

Output

5 5 5

Recycling Rule

If two vectors are of unequal length, the shorter one will be recycled to match the longer vector.

For example, the following vectors vcA and vcB have different lengths, and their sum is computed by recycling values of the shorter vector vcA. Let’s understand with an example.

vcA <- c(10, 20, 30)
vcB <- c(2, 4, 6, 8, 10, 12)

summation <- vcA + vcB
cat(summation)

Output

12 24 36 18 30 42

Here you can see that the first three values of the output are normal, but from the 4th value, it will take the  1st value of the vcA vector for addition and the 4th value of the vcB vector, and their sum is 18. (10 + 8).

The fifth value of the output will take the 2nd value of the 1st vector and the 5th value of the 2nd vector. So the 2nd vcA is 20, and the 5th vcB is 10. So the addition is (10 + 20 = 30). And the same calculation for the last element of the output.

Please note that, If the first vector is smaller than the second vector, then the second vector’s length is multiple of the first vector. Otherwise, the imbalance will be created, and R will throw a warning. Let’s understand the following code.

vcA <- c(10, 20, 30)
vcB <- c(2, 4, 6, 8, 10, 12, 14)

summation <- vcA + vcB
cat(summation)

Output

Warning message:
In vcA + vcB :
longer object length is not a multiple of shorter object length
12 24 36 18 30 42 24

You can see that the R interpreter throws the following warning.

“longer object length is not a multiple of shorter object length.”

That means a longer vector length is not a multiple of a shorter vector length. In our case, the longer vector is vcB, whose length is 7, and the shorter vector length is vcA, whose vector length is 3.

So, the longer vector length should be one of the 3, 6, 9, 12, 15, …, and so on. It should be in multiples of 3.

That is it for Vector Math in R.

Leave a Comment