Comparison &
Logical Operators
Master the building blocks of decision-making in R: comparison operators that test values and logical operators that combine conditions.
What Are Comparison Operators?
Comparison operators compare two values and return a logical result: either TRUE or FALSE. They are the foundation of every if-statement, filter, and conditional expression you will write in R.
Comparison Operators in Action
What Are Logical Operators?
Logical operators let you combine multiple conditions into a single expression. They take TRUE/FALSE inputs and produce a TRUE/FALSE output based on logical rules.
The Truth Table
Single vs Double: & vs &&
R has two versions of AND and OR. The key difference is whether they operate on entire vectors or just the first element.
| Single (& and |) | Double (&& and ||) | |
|---|---|---|
| Operates on | Entire vector (element-wise) | First element only |
| Returns | A vector of TRUE/FALSE | A single TRUE or FALSE |
| Use in | Filtering, vectorized ops | if/else control flow |
| Short-circuit? | No | Yes |
See the Difference in Code
The NOT Operator: !
The ! operator flips a logical value. It turns TRUE into FALSE and FALSE into TRUE. It works on single values and entire vectors.
How to Apply These Operators
Example 1: Simple Comparisons
A student scored 85 on a test. Let's check various conditions about this score.
Example 2: Combining Conditions
Check if a student's score qualifies for an honor roll: score at least 80 AND attendance above 90%.
Example 3: Vectorized Filtering
Filter a vector of temperatures to find days that were warm (above 75) or freezing (below 32).
Short-Circuit Evaluation
The double operators && and || use short-circuit evaluation: R stops checking as soon as it knows the final answer.
Operator Precedence
When you combine multiple operators, R follows a specific order of operations. Highest priority runs first.
Common Mistakes to Avoid
Complete Operator Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | TRUE |
| != | Not equal | 5 != 3 | TRUE |
| < / > | Less / Greater | 3 < 7 | TRUE |
| <= / >= | Less/Greater or equal | 5 >= 5 | TRUE |
| & / && | AND | TRUE & FALSE | FALSE |
| | / || | OR | TRUE | FALSE | TRUE |
| ! | NOT | !TRUE | FALSE |
Question 1 of 5
What does 10 != 10 return in R?
Question 2 of 5
What is the result of TRUE & FALSE?
Question 3 of 5
You have x <- c(3, 7, 2, 9). What does x > 5 return?
Question 4 of 5
Which operator should you use inside an if() statement to combine two conditions?
Question 5 of 5
What does !(5 > 3 | 2 == 2) evaluate to?