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
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
test_expression. This returned vector has element from
x if the corresponding value of
TRUE or from
y if the corresponding value of
FALSE. This is to say, the
i-th element of result will be
TRUE else it will take the value of
y[i]. The vectors
y are recycled whenever necessary.
> 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
(FALSE,FALSE,TRUE ,FALSE). Similarly, the other two vectors in the function argument gets recycled to
("odd","odd","odd","odd") respectively. And hence the result is evaluated accordingly.