Skip to content
Prev 395249 / 398502 Next

if-else that returns vector

?ifelse
'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'.

This is actually rather startling, because elsewhere in the
S (R) language, operands are normally replicated to the length
of the longer.  Thus
    c(1,2,3)*10 + c(5,6)
first (notionally) replicates 10 to c(10,10,10)
and then c(5,6) to c(5,6,5), yielding c(15,26,35).
And this *does* happen, sort of.
=> 5 2 5.
But it *doesn't* apply to the test.

There's another surprise.  Years ago I expected that
all three arguments would be evaluated, then length
adjusted, and then processing would be done.
But the 2nd argument is evaluated (in full) if and only
if some element of the test is true,
and the 3rd argument is evaluated (in full) if and oly
if some element of the test is false.
ifelse(c(NA,NA), stop("true"), stop("false"))
=> c(NA,NA).

At any rate, what you want is if (<test>) <tp> else <fp>



On Fri, 13 Oct 2023 at 09:22, Christofer Bogaso <bogaso.christofer at gmail.com>
wrote: