R ifelse() Function

In R, the ifelse() function is a shorthand vectorized alternative to the standard if...else statement.

Most of the functions in R take a vector as input and return a vectorized output. Similarly, the vector equivalent of the traditional if...else block is the ifelse() function.

The syntax of the ifelse() function is:

ifelse(test_expression, x, y)

The output vector has the element x if the output of the test_expression is TRUE. If the output is FALSE, then the element in the output vector will be y.


Example 1: ifelse() Function for Odd/Even Numbers

# input vector
x <- c(12, 9, 23, 14, 20, 1, 5)

# ifelse() function to determine odd/even numbers
ifelse(x %% 2 == 0, "EVEN", "ODD")

Output

[1] "EVEN" "ODD"  "ODD"  "EVEN" "EVEN" "ODD"  "ODD" 

In this program, we have defined a vector x using the c() function in R. The vector contains a few odd and even numbers.

We then used the ifelse() function which takes the vector x as an input. A logical operation is then performed on x to determine if the elements are odd or even.

For each element in the vector, if the test_expression evaluates to TRUE, then the corresponding output element is "EVEN", else it's "ODD".


Example 2: ifelse() Function for Pass/Fail

# input vector of marks
marks <- c(63, 58, 12, 99, 49, 39, 41, 2)

# ifelse() function to determine pass/fail
ifelse(marks < 40, "FAIL", "PASS")

Output

[1] "PASS" "PASS" "FAIL" "PASS" "PASS" "FAIL" "PASS" "FAIL"

This program determines if the students have passed or failed based on a condition. Here, if the marks in the vector are less than 40, then the student is considered to have failed.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges