ifelse() Function in R (With Examples)

ifelse() function is a conditional statement that performs a certain operation based on a logical test. It allows you to check the conditions and perform operations on every element of a vector at once.

Syntax:

ifelse(Test, Yes, No)

Arguments:

  1. Test = logical condition
  2. Yes = return value if the logical condition is true
  3. No = return value if the logical condition is false

Example 1:

A student appeared for an exam in 5 different subjects and each subject has a passing mark of 33. The marks of each subject are stored in a variable as a vector. To determine if the student has passed or failed in each subject based on a condition, we will use the ifelse() function.

#vector of marks of each subject
marks <- c(46, 78, 33, 15, 47, 31, 58, 9)

#ifelse() function for evaluation
ifelse(marks < 33, "FAIL", "PASS")
Example 1
ifelse() function to evaluate values in a vector.

Example 2:

We can use ifelse() to check if the numbers in a vector are odd or even.

#vector of numbers
numbers <- c(46, 78, 33, 15, 47, 31, 58, 9)

#ifelse() function to check ODD/EVEN
ifelse(numbers%%2==0, "EVEN", "ODD")
Example 2
ifelse() function to check the odd/even numbers.

Was this article helpful?

Leave a Comment