What is the difference between if/else and the vectorised ifelse() in R?

Quick Overview

Explain how R's if/else control flow differs from the vectorised ifelse() function. Tests whether you know what each accepts and returns, how they treat long or missing conditions, which branches get evaluated, and the type pitfalls that make stricter alternatives useful.

What is the difference between if/else and the vectorised ifelse() in R?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What is the difference between `if/else` and the vectorised `ifelse()` in R? ```hint Compare the inputs and outputs Look at the length of the condition each one accepts, and at what each one gives back. ``` ### What a Strong Answer Covers - What each construct accepts as a condition and what it returns - What happens in each case when the condition has more than one element or contains `NA` - Which branch expressions `ifelse()` evaluates, and why that matters for warnings, side effects and cost - The type and attribute pitfalls of `ifelse()` and the stricter alternatives ### Follow-up Questions - Why does `ifelse(d > cutoff, d, NA)` on a `Date` vector return plain numbers, and how would you fix it? - How would you recode a numeric vector into three or more bands without nesting `ifelse()` calls? - When you need one branch decision from a vector condition, what should you write instead of `if (x > 0)`?

Overview: Explain how R's if/else control flow differs from the vectorised ifelse() function. Tests whether you know what each accepts and returns, how they treat long or missing conditions, which branches get evaluated, and the type pitfalls that make stricter alternatives useful.

PracHub logo
General
Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

What is the difference between if/else and the vectorised ifelse() in R?

What a Strong Answer Covers Guidance

  • What each construct accepts as a condition and what it returns
  • What happens in each case when the condition has more than one element or contains NA
  • Which branch expressions ifelse() evaluates, and why that matters for warnings, side effects and cost
  • The type and attribute pitfalls of ifelse() and the stricter alternatives

Follow-up Questions Guidance

  • Why does ifelse(d > cutoff, d, NA) on a Date vector return plain numbers, and how would you fix it?
  • How would you recode a numeric vector into three or more bands without nesting ifelse() calls?
  • When you need one branch decision from a vector condition, what should you write instead of if (x > 0) ?