R Comparison Operators
Comparison Operators
Comparison operators are used to compare two values. This helps us to find answers and make decisions in our programs.
The result of a comparison is either TRUE or FALSE. These are the logical (Boolean) values you learned about in the Booleans chapter.
In the following example, we use the greater than operator (>) to find out if x is greater than y:
Example
x <- 5
y <- 3
x > y
Try it Yourself »
A list of the comparison operators:
| Operator | Name | Example | Description | Try it |
|---|---|---|---|---|
| == | Equal to | x == y | Returns TRUE if the values are equal | Try it » |
| != | Not equal to | x != y | Returns TRUE if the values are not equal | Try it » |
| > | Greater than | x > y | Returns TRUE if the first value is greater than the second | Try it » |
| < | Less than | x < y | Returns TRUE if the first value is less than the second | Try it » |
| >= | Greater than or equal to | x >= y | Returns TRUE if the first value is greater than, or equal to, the second | Try it » |
| <= | Less than or equal to | x <= y | Returns TRUE if the first value is less than, or equal to, the second | Try it » |
Note: Use two equal signs (==) to compare values. One equal sign (=) stores a value in a variable, just like <-.
Compare Strings
You can also compare strings. R is case-sensitive, so "apple" and "Apple" are not equal:
Example
"apple" == "apple"
"apple" == "Apple"
"apple" != "banana"
Try it Yourself »
Real-Life Examples
Comparison operators are often used to check rules, such as if a person is old enough to vote:
Example
age <- 18
age >= 18
age < 18
Try it Yourself »
Another common use is to check if a password is long enough. Here, we use nchar() from the Strings chapter to count the characters:
Example
password <- "abc12"
nchar(password) >= 8
Try it Yourself »
The password only has 5 characters, so the result is FALSE.