you can access the implementation of ifelse
, which is
function (test, yes, no)
{
if (is.atomic(test)) {
if (typeof(test) != "logical")
storage.mode(test) <- "logical"
if (length(test) == 1 && is.null(attributes(test))) {
#... let's skip this part..
}
}
else test <- if (isS4(test))
methods::as(test, "logical")
else as.logical(test)
ans <- test
len <- length(ans)
ypos <- which(test)
npos <- which(!test)
if (length(ypos) > 0L)
ans[ypos] <- rep(yes, length.out = len)[ypos]
if (length(npos) > 0L)
ans[npos] <- rep(no, length.out = len)[npos]
ans
}
<bytecode: 0x00000123e6b7d3a0>
<environment: namespace:base>
So, yes, it is because ifelse
is vectorized - specifically along the condition - and the return object ans
is initialized as a vector of the same length as the condition.
The description of ifelse
states
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.
Let test <- TRUE
. The interesting lines are
ypos <- which(test)
rep(numeric(0), length.out = 1)[ypos]
numeric(0)
, see:c(numeric(0), numeric(0))
. I suppose it tries to vectorize it in a way that is possible.ifelse()
returns a vector of the same length as the test so it can't return a zero length vector.length(TRUE)
is 1.