ifelse()
ifelse(test, yes, no) Returns:
vector · Updated March 13, 2026 · Base Functions conditional vector base
The ifelse() function is R’s vectorized conditional operator. It tests each element of a vector and returns corresponding values from either the yes or no argument. This makes it essential for data transformation tasks where you need to apply conditional logic across entire vectors.
Syntax
ifelse(test, yes, no)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| test | logical vector | — | Condition to evaluate for each element |
| yes | vector | — | Values returned where test is TRUE |
| no | vector | — | Values returned where test is FALSE |
Examples
Basic usage
x <- 1:5
ifelse(x > 2, "big", "small")
# [1] "small" "small" "big" "big" "big"
With strings
scores <- c(85, 92, 78, 55, 90)
result <- ifelse(scores >= 60, "Pass", "Fail")
result
# [1] "Pass" "Pass" "Fail" "Fail" "Pass"
Preserving NA values
x <- c(1, 2, NA, 4, 5)
ifelse(x > 3, "big", "small")
# [1] "small" "small" NA "big" "big"
Common Patterns
Recoding values
colors <- c("red", "blue", "red", "green")
ifelse(colors %in% c("red", "blue"), "primary", "other")
# [1] "primary" "primary" "primary" "other"
Creating flags
temperature <- c(15, 22, 18, 30, 25)
hot_day <- ifelse(temperature > 25, 1, 0)
hot_day
# [1] 0 0 0 1 0
Conditional transformation
prices <- c(10, 50, 100, 200, 25)
discounted <- ifelse(prices > 50, prices * 0.9, prices)
discounted
# [1] 10 45 90 180 25