else if(){} VS ifelse()
Why can we use ifelse()
but not else if(){}
in with()
or within()
statement ?
I heard the first is vectorizable and not the latter. What does it mean ?
Solution 1:
The if
construct only considers the first component when a vector is passed to it, (and gives a warning)
if(sample(100,10)>50)
print("first component greater 50")
else
print("first component less/equal 50")
The ifelse
function performs the check on each component and returns a vector
ifelse(sample(100,10)>50, "greater 50", "less/equal 50")
The ifelse
function is useful for transform
, for instance. It is often useful to
use &
or |
in ifelse
conditions and &&
or ||
in if
.
Solution 2:
Answer for your second part:
*Using if
when x has length of 1 but that of y is greater than 1 *
x <- 4
y <- c(8, 10, 12, 3, 17)
if (x < y) x else y
[1] 8 10 12 3 17
Warning message:
In if (x < y) x else y :
the condition has length > 1 and only the first element will be used
Usingifelse
when x has length of 1 but that of y is greater than 1
ifelse (x < y,x,y)
[1] 4 4 4 3 4