x
or
y
, depending on
test
. Allows multiple tests.
ifelse1(test, x, y, ...) # actual arguments ifelse1(test, x, y) # usual way to use ifelse1(test1, x, test2, v, w) # two conditions
TRUE
return
x
test
is
TRUE
.
test
is
FALSE
. If there are 5 or more arguments, then
a logical value
x
or
y
. With
k
arguments,
one of arguments 2, 4, ..., k-1, k.
This is equivalent to
{if(test) x else y}
. The main advantage of using this function is
better formatting, and a more natural syntax when the result is being
assigned; see examples below.
With 5 arguments, this is equivalent to
{if(test1) x else if(test2) u else v}
(where arguments are given by name, not position).
In
ifelse1
,
test
should be a single value, and the calculations
for
y
(or
x
) are not performed if it is not selected.
In contrast, for
ifelse
,
test
is normally a vector, both
x
and
y
are evaluated, even if not used, and
x
and
y
are vectors
the same length as
test
.
x <- 1:3; y <- matrix(1:2) # so example runs # Here is code from %*%.default { # must enclose in {}, so example runs if(length(x) == nrow(y)) dim(x) <- c(1, length(x)) else dim(x) <- c(length(x), 1) } # Using if ... else ... dim(x) <- { if(length(x) == nrow(y)) c(1, length(x)) else c(length(x), 1) } # Using ifelse1 dim(x) <- ifelse1(length(x) == nrow(y), c(1, length(x)), c(length(x), 1))