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.

Types of operators
Types of operators

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:

Types of arithmetic operators
Types of arithmetic operators

Let’s have a look at the code where we use these operators.

Press + to interact
number1 <- 10
number2 <- 3
# Addition
number1 + number2
# Subtraction
number1 - number2
# Multiplication
number1 * number2
# Division
number1 / number2
# Exponent
number1 ^ number2
# Modulus
number1 %% number2
# Integer Division
number1 %/% 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!

Press + to interact
vector1 <- c(5, 10, 15)
vector2 <- c(3, 6, 9)
# Addition
vector1 + vector2
# Subtraction
vector1 - vector2
# Multiplication
vector1 * vector2
# Division
vector1 / vector2
# Exponent
vector1 ^ vector2
# Modulus
vector1 %% vector2
# Integer Division
vector1 %/% 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.

Press + to interact
myVector <- c(5, 10, 15)
number <- 3
# Addition
myVector + number
# Subtraction
myVector - number
# Multiplication
myVector * number
# Division
myVector / number
# Exponent
myVector ^ number
# Modulus
myVector %% number
# Integer Division
myVector %/% 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.

Press + to interact
vector1 <- c(5, 10, 15, 20)
vector2 <- c(3, 6, 9)
# Addition
vector1 + vector2