Arithmetic Operators
In this lesson, we will learn the basic arithmetic operations in R and how to use them.
We'll cover the following
R has many operators that carry out different arithmetic and logical operations. An operator is a symbol that guides the compiler to perform specific arithmetic or logical manipulations.
Operators in R can be classified into the following categories.
What are Arithmetic Operators?
Arithmetic operators are used for carrying out mathematical operations like addition and subtraction. The following are some of the arithmetic operators used in R language:
Let’s have a look at the code where we use these operators.
number1 <- 10number2 <- 3# Additionnumber1 + number2# Subtractionnumber1 - number2# Multiplicationnumber1 * number2# Divisionnumber1 / number2# Exponentnumber1 ^ number2# Modulusnumber1 %% number2# Integer Divisionnumber1 %/% number2
Another method to calculate exponents in R is to use
**
operator.
Now, let’s try arithmetic operators on vectors. The operators act on each element of the vector.
The output of performing arithmetic operations on vectors is a vector!
vector1 <- c(5, 10, 15)vector2 <- c(3, 6, 9)# Additionvector1 + vector2# Subtractionvector1 - vector2# Multiplicationvector1 * vector2# Divisionvector1 / vector2# Exponentvector1 ^ vector2# Modulusvector1 %% vector2# Integer Divisionvector1 %/% vector2
What if we perform calculations with one vector and one variable number?
Here the variable number
performs calculations with each element of the vector.
myVector <- c(5, 10, 15)number <- 3# AdditionmyVector + number# SubtractionmyVector - number# MultiplicationmyVector * number# DivisionmyVector / number# ExponentmyVector ^ number# ModulusmyVector %% number# Integer DivisionmyVector %/% number
However, for calculations between variable length vectors (that are not multiples of each other) the compiler throws a warning message stating that the longer object length is not a multiple of shorter object length. In the code snippet below, the first vector has a length of 4 and the second vector has a length of 3. Neither of the lengths are multiples of each other, which is why the compiler throws a warning.
vector1 <- c(5, 10, 15, 20)vector2 <- c(3, 6, 9)# Additionvector1 + vector2