Comparison Operators in R

The Comparison operators in R Programming are mostly used either in If Conditions or Loops. The R Relational operators are commonly used to check the relationship between two variables.

  • If the relation is true, then it returns Boolean True
  • If the relation is false, it returns Boolean False.

The table below shows all the Relational Operators in R Programming with examples.

Comparison Operators in RUsageDescriptionExample
>i > ji is greater than j25 > 14 returns True
<i < ji is less than j25 < 14 returns False
>=i >= ji is greater than or equal to j25 >= 14 returns True
<=i <= ji is less than or equal to j25 <= 14 return False
==i == ji is equal to j25 == 14 returns False
!=i != ji is not equal to j25 != 14 returns True

Comparison Operators in R Programming Example

This example helps you to understand the Relational or Comparison Operators in R Programming language practically. For this example, We are using two variables, a and b, and their respective values are 15 and 12. We are going to use these two variables to perform various relational operations present in R Programming.

# Example for Comparison Operators in R Programming
a <- 15
b <- 12

print(paste("Output of 15 > 12 is : ", a > b))
print(paste("Output of 15 < 12 is : ", a < b))
print(paste("Output of 15 >= 12 is : ", a >= b))
print(paste("Output of 15 <= 12 is : ", a <= b))
print(paste("Output of 15 Equal to 12 is : ", a == b))
print(paste("Output of 15 Not Equal to 12 is : ", a != b))
Relational or Comparison Operators in R Programming 1

We assigned two integer values a, b, and we assigned the values 15 and 12 using the below statement.

a <- 15
b <- 12

In the next lines, We checked these values against each comparison operator (relational operator) present in the R Programming language.

R Comparison Operators in IF Statement

This example helps you to understand how to use Comparison operators inside the If statements. For this example, We are using two variables, x and y, with their values of 25 and 25. We are going to use these two variables inside the If condition, along with one of the relational or comparison operators present in R Programming to check the condition.

# Example for Relational Operators in R Programming
x <- 25
y <- 25
if(x == y) {
  print("x is Equal to y")
} else {
  print("x is NOT Equal to y")
}
Relational and Comparison Operators in R Programming 2

In this R relational operators example, we assigned two integer values x, y, and assigned the values 25 and 25 using the below statement.

x <- 25
y <- 25

Within the If Condition

If x is equal to y, then the first print statement executed

print("x is Equal to y")

If the first condition fails, then the second print statement executed.

print("x is NOT Equal to y")

Here 25 is equal to 25, so the First print statement is printed.