ifelse
returns a value with the same shape as
test
which is filled with elements selected
from either yes
or no
depending on whether the element of test
is TRUE
or FALSE
.
ifelse(test, yes, no)
test
.test
."class"
) as test
and data values from the values of
yes
or no
. The mode of the answer will be coerced from
logical to accommodate first any values taken from yes
and then
any values taken from no
.
test
(see the
examples), and the class attribute (see oldClass
) of the
result is taken from test
and may be inappropriate for the
values selected from yes
and no
. Sometimes it is better to use a construction such as
(tmp <- yes; tmp[!test] <- no[!test]; tmp), possibly extended to handle missing values in
test
.yes
or no
are too short, their elements are recycled.
yes
will be evaluated if and only if any element of test
is true, and analogously for no
. Missing values in test
give missing values in the result.
if
.
x <- c(6:-4)
sqrt(x) #- gives warning
sqrt(ifelse(x >= 0, x, NA)) # no warning
## Note: the following also gives the warning !
ifelse(x >= 0, sqrt(x), NA)
## example of different return modes:
yes <- 1:3
no <- pi^(0:3)
typeof(ifelse(NA, yes, no)) # logical
typeof(ifelse(TRUE, yes, no)) # integer
typeof(ifelse(FALSE, yes, no)) # double
Run the code above in your browser using DataLab