R ifelse() Function

In this article, you will learn about the ifelse() function in R programming with the help of examples.

Vectors form the basic building block of R programming. Most of the functions in R take vectors as input and output a resultant vector.

This vectorization of code will be much faster than applying the same function to each element of the vector individually.

Similar to this concept, there is a vector equivalent form of the if…else statement in R, the ifelse() function.

The ifelse() function is a conditional function in R that allows you to perform element-wise conditional operations on vectors or data frames.


Syntax of ifelse() function

The syntax of the ifelse() function is:

ifelse(test_expression, x, y)

Here,

  • text_expression - A logical condition or a logical vector that specifies the condition to be evaluated. It can be a single logical value or a vector of logical values.
  • x - The value or expression to be returned when the condition is true. It can be a single value, vector, or an expression.
  • y - The value or expression to be returned when the condition is false. It can be a single value, vector, or an expression.

The return value is a vector with the same length as test_expression.

This is to say, the ith element of the result will be x[i] if test_expression[i] is TRUE else it will take the value of y[i].


Example: ifelse() function

# create a vector
a = c(5,7,2,9)
# check if each element in a is even or odd
ifelse(a %% 2 == 0,"even","odd")

Output

[1] "odd"  "odd"  "even" "odd" 

In the example, a is a vector with values [5, 7, 2, 9].

When we apply the condition a %% 2 == 0, it checks each element in a to see if it is divisible by 2 without a remainder. This results in a logical vector: [FALSE, FALSE, TRUE, FALSE].

Now, the ifelse() function takes this logical vector as the condition. It also takes two other vectors: ["even", "even", "even", "even"] and ["odd", "odd", "odd", "odd"].

Since the condition vector has a length of 4, the other two vectors are recycled to match this length.

The ifelse() function then evaluates each element of the condition vector. If the element is TRUE, it chooses the corresponding element from the "even" vector. If the element is FALSE, it chooses the corresponding element from the "odd" vector.

Did you find this article helpful?