0
0
R-programmingHow-ToBeginner · 3 min read

How to Use ifelse Function in R: Syntax and Examples

In R, the ifelse function tests a condition and returns one value if the condition is TRUE and another if FALSE. It works element-wise on vectors, making it useful for quick conditional checks and replacements.
📐

Syntax

The ifelse function has three parts:

  • test_expression: The condition to check (TRUE or FALSE).
  • yes: Value returned if the condition is TRUE.
  • no: Value returned if the condition is FALSE.
r
ifelse(test_expression, yes, no)
💻

Example

This example shows how to use ifelse to label numbers as 'Even' or 'Odd'. It checks each number in the vector and returns the corresponding label.

r
numbers <- 1:5
labels <- ifelse(numbers %% 2 == 0, "Even", "Odd")
print(labels)
Output
[1] "Odd" "Even" "Odd" "Even" "Odd"
⚠️

Common Pitfalls

Common mistakes include:

  • Using ifelse for complex multiple conditions instead of case_when or nested ifelse.
  • Not vectorizing the condition, which can cause unexpected results.
  • Mixing data types in yes and no arguments, leading to type coercion.
r
x <- c(1, 2, 3)
# Wrong: mixing types
result_wrong <- ifelse(x > 2, "Yes", 0)
print(result_wrong)

# Right: consistent types
result_right <- ifelse(x > 2, "Yes", "No")
print(result_right)
Output
[1] "1" "2" "Yes" [1] "No" "No" "Yes"
📊

Quick Reference

Tips for using ifelse:

  • Always ensure yes and no return values have compatible types.
  • Use vectorized conditions for efficient code.
  • For multiple conditions, consider nested ifelse or dplyr::case_when().

Key Takeaways

Use ifelse for simple vectorized conditional checks in R.
Ensure the yes and no values have compatible data types to avoid coercion.
ifelse works element-wise on vectors, returning a vector of results.
For complex conditions, use nested ifelse or case_when for clarity.
Test conditions carefully to avoid unexpected results with non-vectorized inputs.