Vector Arithmetic Operations
We can perform arithmetic operations on vectors, like addition, subtraction, multiplication and division.
Please note that the two vectors should be of same length and same type. Or one of the vectors can be an atomic value of same type.
If the vectors are not of same length, then Vector Recycling happens implicitly.
Addition
Addition operator takes two vectors as operands, and returns the result of sum of two vectors.
a + b
Example
In the following program, we create two integer vectors and add them using Addition Operator.
Example.R
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3, 5, 7, 9)
result <- a + b
print(result)
Output
[1] 11 23 35 47 59
Subtraction
Subtraction operator takes two vectors as operands, and returns the result of difference of two vectors.
a - b
Example
In the following program, we create two integer vectors and find their different using Subtraction Operator.
Example.R
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3, 5, 7, 9)
result <- a - b
print(result)
Output
[1] 9 17 25 33 41
Multiplication
Multiplication operator takes two vectors as operands, and returns the result of product of two vectors.
a * b
Example
In the following program, we create two integer vectors and find their product using Multiplication Operator.
Example.R
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3, 5, 7, 9)
result <- a * b
print(result)
Output
[1] 10 60 150 280 450
Division
Division operator takes two vectors are operands, and returns the result of division of two vectors.
a + b
Example
In the following program, we create two integer vectors and divide them using Division Operator.
Example.R
a <- c(10, 20, 30, 40, 50)
b <- c(1, 3, 5, 7, 9)
result <- a / b
print(result)
Output
[1] 10.000000 6.666667 6.000000 5.714286 5.555556
Conclusion
In this R Tutorial, we learned about Arithmetic Operations of Vectors with the help of examples.