R ifelse() Function
In this article, you’ll learn about ifelse() function. This is a shorthand function to the traditional if…else statement.
Vectors form the basic building block of R programming.
Most of the functions in R take vector 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
Syntax of ifelse() function
ifelse(test_expression, x, y)
test_expression must be a logical vector (or an object that can be coerced to logical). The return value is a vector with the same length as
This returned vector has element from
x if the corresponding value of
TRUE or from
y if the corresponding value of
This is to say, the
i-th element of result will be
TRUE else it will take the value of
y are recycled whenever necessary.
Example: ifelse() function
> a = c(5,7,2,9) > ifelse(a %% 2 == 0,"even","odd")  "odd" "odd" "even" "odd"
In the above example, the
a %% 2 == 0 which will result into the vector
Similarly, the other two vectors in the function argument gets recycled to
And hence the result is evaluated accordingly.
R if...else Statement
R for Loop