Vectorized vs.
Short-Circuit Operators
Learn when R processes every element of a vector and when it stops early: the key distinction between & | and && ||.
What Are Logical Operators?
Logical operators combine or negate TRUE and FALSE values. In R, they are the foundation of conditional logic: filtering data, controlling program flow, and writing tests.
Vectors: R's Core Data Structure
Almost everything in R is a vector: a sequence of values of the same type. Even a single number like 5 is a vector of length 1.
Two Families of Logical Operators
The Vectorized Rule: & and |
The Short-Circuit Rule: && and ||
Key Distinction at a Glance
| Feature | Vectorized (& |) | Short-Circuit (&& ||) |
|---|---|---|
| Input length | Any length vector | Checks first element only |
| Output length | Same as input | Always length 1 |
| Evaluates both sides? | Always | Only if needed |
| Primary use | Data filtering, subsetting | if/else conditions |
| Example context | df[df$x \(> 0\) & df$y \(< 10\), ] | if (\(n > 0\) && \(\frac{x}{n} > 0.5\)) |
Why Short-Circuiting Matters
Short-circuiting is not just an optimisation: it can prevent errors. If the left side of && is FALSE, the right side is skipped entirely, even if it would have caused a crash.
How to Choose the Right Operator
Example 1: Vectorized AND
Example 2: Short-Circuit AND
Example 3: Short-Circuit OR in Action
Example 4: Filtering a Data Frame
Decision Flowchart
Common Mistakes
Summary Table
| Property | & | | | && | || |
|---|---|---|---|---|
| Type | Vectorized AND | Vectorized OR | Short-circuit AND | Short-circuit OR |
| Elements checked | All | All | First only | First only |
| Return length | \(n\) | \(n\) | 1 | 1 |
| Short-circuits? | No | No | Yes | Yes |
| Best for | Filtering | Filtering | if/while | if/while |
Question 1 of 5
What does c(TRUE, FALSE) & c(FALSE, TRUE) return?
Question 2 of 5
Which operator should you use inside an if() statement?
Question 3 of 5
What does FALSE && stop("error") produce?
Question 4 of 5
You want to filter a data frame to rows where age > 18 and score > 80. Which operator is correct?
Question 5 of 5
What is the key reason && and || are called "short-circuit" operators?