01 / 21
T F test

R's ifelse()
Function

Master vectorized conditional assignment to transform entire vectors in a single line: no loops required.

R Programming

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.

ifelse(test, yes, no)

Why Vectorization Matters

Speed
Vectorized code runs in optimized C under the hood: far faster than an R-level loop over each element.
Clarity
One expressive line replaces a multi-line for loop, making your intent immediately obvious to readers.
Safety
No risk of off-by-one indexing errors or forgetting to pre-allocate a results vector.

How ifelse() Flows

Input Vector 3 7 2 9 5
test: \( x > 5 \)
FALSE TRUE FALSE TRUE FALSE Result Vector "no" "yes" "no" "yes" "no"
ifelse(\( x > 5 \), "yes", "no")

The Formal Syntax

ifelse(test, yes, no)
test
A logical vector (or an expression that produces one). Each element is TRUE or FALSE.
yes
Value(s) returned where the test is TRUE. Can be a scalar or a vector the same length as test.
no
Value(s) returned where the test is FALSE. Same recycling rules apply as for yes.

Output Type Behavior

test vector TRUE FALSE yes value no value result vector same length as test, element-by-element merge

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()

1
Identify your vector. What data are you transforming? (e.g., a column of scores)
2
Write the test expression. It must produce a logical vector: TRUE / FALSE for each element.
3
Choose the "yes" value. What should replace each TRUE position? (scalar or vector)
4
Choose the "no" value. What should replace each FALSE position?
5
Assemble the call. ifelse(test, yes, no) and assign the result.

Example 1: Pass / Fail

scores <- c(82, 45, 91, 60, 38) result <- ifelse(scores >= 60, "Pass", "Fail") result # [1] "Pass" "Fail" "Pass" "Pass" "Fail"

Example 2: Capping Values

temps <- c(68, 104, 72, 99, 110) # Cap temperatures at 100 capped <- ifelse(temps > 100, 100, temps) capped # [1] 68 100 72 99 100

Example 3: Nested ifelse()

scores <- c(95, 72, 58, 83) grade <- ifelse(scores >= 90, "A", ifelse(scores >= 80, "B", ifelse(scores >= 70, "C", "F"))) grade # [1] "A" "C" "F" "B"

Handling NA Values

x <- c(10, NA, 3, 7) ifelse(x > 5, "big", "small") # [1] "big" NA "small" "big"
# Safe version: replace NA first ifelse(is.na(x), "unknown", ifelse(x > 5, "big", "small")) # [1] "big" "unknown" "small" "big"

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).

x <- c(1, 2, 3, 4) y <- c(10, 20, 30, 40) # Scalar recycled into both positions ifelse(x > 2, 0, x) # [1] 1 2 0 0 # Vector yes, vector no ifelse(x > 2, y, x) # [1] 1 2 30 40

Using ifelse() in Data Frames

# Create a small data frame df <- data.frame( name = c("Alice", "Bob", "Cara"), score = c(88, 55, 73) ) # Add a new column df$status <- ifelse(df$score >= 60, "Pass", "Fail") df # name score status # 1 Alice 88 Pass # 2 Bob 55 Fail # 3 Cara 73 Pass

Common Mistakes

✕ Using if/else on a vector
Writing if(x \( > \) 5) when x has multiple elements only checks the first element and throws a warning.
✕ Ignoring NA propagation
ifelse() returns NA wherever test is NA. Forgetting to handle missing values can silently corrupt results.
✕ Type coercion surprises
Mixing types in yes/no (e.g., numeric and character) forces coercion: 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 of
ifelse(x \( > \) 5, "high", "low")?

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 does
ifelse(temps \( > \) 100, 100, temps) return?