Does ifelse
really calculate both the yes
and no
vectors -- as in, the entirety of each vector?
Or does it just calculate some values from each vector?
Also, is ifelse
really that slow?
Does ifelse
really calculate both the yes
and no
vectors -- as in, the entirety of each vector?
Or does it just calculate some values from each vector?
Also, is ifelse
really that slow?
Yes. (With exception)
ifelse
calculates both itsyes
value and itsno
value. Except in the case where thetest
condition is either allTRUE
or allFALSE
.We can see this by generating random numbers and observing how many numbers are actually generated. (by reverting the
seed
).Gives the following output:
We can also see it in the source code itself:
Notice that
yes
andno
are computed only if there is some non-NA
value oftest
that isTRUE
orFALSE
(respectively).At which point -- and this is the imporant part when it comes to efficiency -- the entirety of each vector is computed.
Ok, but is it slower?
Lets see if we can test it:
These two statements generate the same results
but one is twice as fast as the other