In the R programming language, relational operators are used to compare values and return logical values (TRUE or FALSE) based on the specified condition. These operators are commonly used in conditional statements, loops, and data filtering operations. Here are the most commonly used relational operators in R:
Equality Operator (==): This operator is used to check if two values are equal.
x == y
Inequality Operator (!=): This operator is used to check if two values are not equal.
x != y
Greater Than Operator (>): This operator is used to check if the left operand is greater than the right operand.
x > y
Less Than Operator (<): This operator is used to check if the left operand is less than the right operand.
x < y
Greater Than or Equal To Operator (>=): This operator is used to check if the left operand is greater than or equal to the right operand.
x >= y
Less Than or Equal To Operator (<=): This operator is used to check if the left operand is less than or equal to the right operand.
x <= y
These relational operators can be used with various data types, such as numeric, character, logical, and more. When comparing character strings, R compares them lexicographically based on their alphabetical order.
Here are some examples of how these operators can be used in R:
# Numeric comparisons
a <- 5
b <- 10
a == b # FALSE
a != b # TRUE
a > b # FALSE
a < b # TRUE
a >= b # FALSE
a <= b # TRUE
# Character string comparisons
str1 <- “apple”
str2 <- “banana”
str1 == str2 # FALSE (lexicographical comparison)
str1 < str2 # TRUE (again, lexicographical comparison)
Relational operators are often used in combination with logical operators (e.g., AND, OR) to create complex conditional statements for data manipulation and analysis in R.