Relational Operators
In this lesson, we will learn the basic relational operations in R and how to use them.
We'll cover the following
What are Relational Operators?
Relational Operators are used for comparing objects. They return a boolean variable, i.e., TRUE
or FALSE
.
Let’s have a look at the code:
number1 <- 10number2 <- 3# Equal tonumber1 == number2# Not equal tonumber1 != number2# Less thannumber1 < number2# Less than equal tonumber1 <= number2# Greater thannumber1 > number2# Greater than equal tonumber1 >= 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!
vector1 <- c(5, 10, 15)vector2 <- c(3, 6, 9)# Equal tovector1 == vector2# Not equal tovector1 != vector2# Less thanvector1 < vector2# Less than equal tovector1 <= vector2# Greater thanvector1 > vector2# Greater than equal tovector1 >= 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 <- 3number %in% myVector
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.
vector1 <- c(5, 3, 15)vector2 <- c(3, 10)vector2 %in% vector1 # 3 is present in vector1 but 10 is not present in vector2