ifelse()
ifelse asks the same yes-or-no question about every item in a list and picks one of two answers for each. It is like a teacher marking a whole class pass or fail in one go.
In this page:
Syntax
result <- ifelse(condition, value_if_true, value_if_false)
ifelse()
ifelse(condition, yes, no) is a vectorized version of if/else, evaluating a condition element-wise across a whole vector and returning a vector of results.
This avoids writing a loop to apply conditional logic to every element. It's one of R's most common idioms for transforming data based on a condition.
Note:
Use ifelse() when you need to apply a condition across an entire vector at once, not just a single value.
Example: ifelse()
scores <- c(95, 60, 78, 40, 88)
results <- ifelse(scores >= 70, "Pass", "Fail")
print(results)
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
ifon a whole vector whenifelse()is needed for element-wise results. - Expecting
ifelse()to keep the types of both branches, when the result takes a type based on the test and the chosen values. - Forgetting that a
NAin the test givesNAin the result.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: