Relational Operators

In this lesson, we will learn the basic relational operations in R and how to use them.

What are Relational Operators?

Relational Operators are used for comparing objects. They return a boolean variable, i.e., TRUE or FALSE.

Relational operators in R language
Relational operators in R language

Let’s have a look at the code:

Press + to interact
number1 <- 10
number2 <- 3
# Equal to
number1 == number2
# Not equal to
number1 != number2
# Less than
number1 < number2
# Less than equal to
number1 <= number2
# Greater than
number1 > number2
# Greater than equal to
number1 >= number2

If you use a relational operator to compare vectors, R will do element-wise comparisons.

The output of performing relational operations on two vectors is a vector!

Press + to interact
vector1 <- c(5, 10, 15)
vector2 <- c(3, 6, 9)
# Equal to
vector1 == vector2
# Not equal to
vector1 != vector2
# Less than
vector1 < vector2
# Less than equal to
vector1 <= vector2
# Greater than
vector1 > vector2
# Greater than equal to
vector1 >= vector2

The %in% operator

The %in% operator is used only on vectors and it is the only operator that does not do normal element-wise execution.

%in% checks whether the value(s) on the left side are present on the right side. This means %in% tests whether each value on the left is somewhere in the vector on the right:

myVector <- c(5, 3, 15)
number <- 3
number %in% myVector
Check whether the number is in the vector

When using relational operators to compare vectors, if the two vectors are of unequal length, R tries to equalize them by replicating the smaller one.

If the vector on the left-hand side has multiple elements, each element is searched in the vector on the right-hand side. Individual TRUE or FALSE values are produced as a result.

Press + to interact
vector1 <- c(5, 3, 15)
vector2 <- c(3, 10)
vector2 %in% vector1 # 3 is present in vector1 but 10 is not present in vector2