R's ifelse()
Function
Master vectorized conditional assignment to transform entire vectors in a single line: no loops required.
What Is ifelse()?
ifelse() is a built-in R function that takes a logical vector, checks each element, and returns the "yes" value where the condition is TRUE and the "no" value where it is FALSE.
Why Vectorization Matters
How ifelse() Flows
The Formal Syntax
Output Type Behavior
if/else vs ifelse()
| if/else | ifelse() | |
|---|---|---|
| Type | Control-flow statement | Vectorized function |
| Input | Single logical value | Logical vector (any length) |
| Output | Runs a code block | Returns a vector |
| Use case | Branching program logic | Transforming data columns |
| Speed on vectors | Needs a loop | Instant (C-level) |
How to Apply ifelse()
ifelse(test, yes, no) and assign the result.Example 1: Pass / Fail
Example 2: Capping Values
Example 3: Nested ifelse()
Handling NA Values
Vector Recycling
When yes or no is a scalar (length 1), R recycles it to match the length of test. When they are vectors, they must be the same length as test (or R recycles with a warning).
Using ifelse() in Data Frames
Common Mistakes
if(x \( > \) 5) when x has multiple elements only checks the first element and throws a warning.ifelse(TRUE, 1, "a") returns "1" (character).Summary Cheat Sheet
| Feature | Details |
|---|---|
| Syntax | ifelse(test, yes, no) |
| Input | Logical vector of any length |
| Output | Vector same length as test |
| NA handling | NA in test produces NA in output |
| Nesting | Nest in no for multi-category |
| Type rule | Keep yes/no same type |
| Best for | Column-wise transformations |
Question 1 of 5
What does ifelse() return when the test value at a position is NA?
Question 2 of 5
Given x <- c(4, 8, 2, 6), what is the output ofifelse(x \( > \) 5, "high", "low")?
x \( > \) 5 produces FALSE, TRUE, FALSE, TRUE. So positions 1 and 3 get "low", positions 2 and 4 get "high": "low" "high" "low" "high".Question 3 of 5
What is the key difference between if/else and ifelse()?
Question 4 of 5
What happens when you run ifelse(TRUE, 42, "hello")?
Question 5 of 5
Given temps <- c(68, 104, 72), what doesifelse(temps \( > \) 100, 100, temps) return?
temps \( > \) 100 gives FALSE, TRUE, FALSE. Position 1 and 3 keep their original values (68, 72) from the no argument. Position 2 is capped at 100 from the yes argument.