A Vectorized if-then-else: The ifelse() Function
In addition to the usual if-then-else construct found in most languages, R also includes a vectorized version, the
ifelse() function. The form is as follows:
b is a Boolean vector, and
v are vectors.
The return value is itself a vector; element
b[i] is true, or
b[i] is false. The concept is pretty abstract, so let’s go right to an example:
> x <- 1:10 > y <- ifelse(x %% 2 == 0,5,12) # %% is the mod operator > y  12 5 12 5 12 5 12 5 12 5
Here, we wish to produce a vector in which there is a 5 wherever
x is even or a 12 wherever
x is odd. So, the actual argument corresponding to the formal argument
b is (F,T,F,T,F,T,F,T,F,T). The second actual argument, ...