R Program to Add Two Vectors

In this example, you'll learn to add two vectors using R operators.

To understand this example, you should have the knowledge of the following R programming topics:

We can add two vectors together using the + operator.

One thing to keep in mind while adding (or other arithmetic operations) two vectors together is the recycling rule.

If the two vectors are of equal length then there is no issue. But if the lengths are different, the shorter one is recycled (repeated) until its length is equal to that of the longer one.

This recycling process will give a warning if the longer vector is not an integral multiple of the shorter one.

Example: Add Two Vectors

> x
[1] 3 6 8
> y
[1] 2 9 0
> x + y
[1]  5 15  8
> x + 1    # 1 is recycled to (1,1,1)
[1] 4 7 9
> x + c(1,4)    # (1,4) is recycled to (1,4,1) but warning issued
[1]  4 10  9
Warning message:
In x + c(1, 4) :
longer object length is not a multiple of shorter object length

As we can see above the two vectors x and y are of equal length so they can be added together without difficulty.

The expression x + 1 also works fine because the single 1 is recycled into a vector of three 1's.

Similarly, in the last example, a two element vector is recycled into a three element vector. But a warning is issued in this case as 3 is not an integral multiple of 2.

Did you find this article helpful?