How to Add Two Vectors in R (4 Examples)

To add vectors in R, you can use the “+” operator. When adding two vectors, if they are of equal length, the addition operation is performed directly. However, if the lengths are different, the shorter vector is padded (repeated) to match the length of the longer vector. This ensures that the addition operation is performed correctly.

Example 1: R Program to add two vectors

fv <- 1:4
cat("The first vector is: ", fv, "\n")
sv <- 5:8
cat("The second vector is: ", sv, "\n")

add <- fv + sv
cat("The final vector is: ", add)

Output

The first vector is: 1 2 3 4
The second vector is: 5 6 7 8
The final vector is: 6 8 10 12

Example 2: Adding two vectors of different lengths

What if two vectors have different lengths? Then we will get a warning message: longer object length is not a multiple of shorter object length.

fv <- 1:4
cat("The first vector is: ", fv, "\n")
sv <- 5:13
cat("The second vector is: ", sv, "\n")

add <- fv + sv
cat("The final vector is: ", add)

Output

The first vector is: 1 2 3 4
The second vector is: 5 6 7 8 9 10 11 12 13
Warning message:
In fv + sv :
longer object length is not a multiple of shorter object length
The final vector is: 6 8 10 12 10 12 14 16 14

You can see that the addition takes place until both vectors have the same length; after that, the longer-length vector’s elements are added as it is to the final sum vector.

Example 3: Adding vectors of different DataTypes

Adding two vectors of different types, such as a vector of integer and string, gives the binary operator an error as an Error in fv + sv non-numeric argument.

fv <- 1:4
cat("The first vector is: ", fv, "\n")
sv <- c("Snape", "Minerva", "Horace", "Lupin")
cat("The second vector is: ", sv, "\n")

add <- fv + sv
cat("The final vector is: ", add)

Output

The first vector is: 1 2 3 4
The second vector is: Snape Minerva Horace Lupin
Error in fv + sv : non-numeric argument to binary operator
Execution halted

As expected, we got non-numeric argument to binary operatorerror.

Example 4: Adding Two Vectors of DataType Character

Adding vectors of string gives the same error as adding vectors of integer and string datatypes.

dv <- rep("Grogu", 3)
cat("The first vector is: ", dv, "\n")
iv <- rep("Grogu", 3)
cat("The second vector is: ", iv, "\n")
add <- dv + iv
print(add)
cat("The final vector is: ", add)

Output

The first vector is: MJ MJ MJ
The second vector is: MJ MJ MJ
Error in dv + iv : non-numeric argument to binary operator
Execution halted

And we get the same error: non-numeric argument to the binary operator.

That’s it.

Leave a Comment