Introduction
In this chapter, you will learn about relational operators in R. Relational operators are used to compare two values and determine the relationship between them. These operators return a logical value (TRUE
or FALSE
) based on the comparison. Understanding how to use relational operators is essential for making decisions and controlling the flow of your R programs.
Relational Operators in R
1. Equal to (==
)
The equal to operator checks if two values are equal.
Example:
# Equal to
a <- 10
b <- 10
result <- a == b
print(result) # Output: TRUE
2. Not equal to (!=
)
The not equal to operator checks if two values are not equal.
Example:
# Not equal to
a <- 10
b <- 5
result <- a != b
print(result) # Output: TRUE
3. Greater than (>
)
The greater than operator checks if the value on the left is greater than the value on the right.
Example:
# Greater than
a <- 10
b <- 5
result <- a > b
print(result) # Output: TRUE
4. Less than (<
)
The less than operator checks if the value on the left is less than the value on the right.
Example:
# Less than
a <- 10
b <- 20
result <- a < b
print(result) # Output: TRUE
5. Greater than or equal to (>=
)
The greater than or equal to operator checks if the value on the left is greater than or equal to the value on the right.
Example:
# Greater than or equal to
a <- 10
b <- 10
result <- a >= b
print(result) # Output: TRUE
6. Less than or equal to (<=
)
The less than or equal to operator checks if the value on the left is less than or equal to the value on the right.
Example:
# Less than or equal to
a <- 10
b <- 15
result <- a <= b
print(result) # Output: TRUE
Example Program with Relational Operators
Here is an example program that demonstrates the use of relational operators in R:
# R Program to Demonstrate Relational Operators
# Declare variables
a <- 25
b <- 20
# Perform relational operations
equal_result <- a == b # Equal to
not_equal_result <- a != b # Not equal to
greater_result <- a > b # Greater than
less_result <- a < b # Less than
greater_equal_result <- a >= b # Greater than or equal to
less_equal_result <- a <= b # Less than or equal to
# Print results
print(paste("a == b:", equal_result)) # Output: a == b: FALSE
print(paste("a != b:", not_equal_result)) # Output: a != b: TRUE
print(paste("a > b:", greater_result)) # Output: a > b: TRUE
print(paste("a < b:", less_result)) # Output: a < b: FALSE
print(paste("a >= b:", greater_equal_result)) # Output: a >= b: TRUE
print(paste("a <= b:", less_equal_result)) # Output: a <= b: FALSE
Conclusion
In this chapter, you learned about relational operators in R, including equal to, not equal to, greater than, less than, greater than or equal to, and less than or equal to. These operators are essential for comparing values and making decisions in your R programs. By mastering these operators, you can control the flow of your code and implement logic based on comparisons.