← Back to R Course | Chapter 4: Control Flow | Lesson 2 of 6

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:

  1. ifelse()
Syntax
r
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()

markup
scores <- c(95, 60, 78, 40, 88)

results <- ifelse(scores >= 70, "Pass", "Fail")
print(results)
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
  1. Using if on a whole vector when ifelse() is needed for element-wise results.
  2. Expecting ifelse() to keep the types of both branches, when the result takes a type based on the test and the chosen values.
  3. Forgetting that a NA in the test gives NA in the result.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.