Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 785
Wicelo Avatar asked Jun 22 '13 16:06

Wicelo


People also ask

What is difference between if and Ifelse?

With the if statement, a program will execute the true code block or do nothing. With the if/else statement, the program will execute either the true code block or the false code block so something is always executed with an if/else statement.

Which is better if else or if Elseif?

In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.

What is the difference between else if and nested IF?

There's not really a difference. The if, else if, else conditional is actually the same as the nested one with one of the {} enclosures removed.

What does the Ifelse function do?

ifelse evaluates a set of if, then expression pairings, and returns the value of the then argument for the first if argument that evaluates to true. The remaining arguments in the list are not evaluated. If none of the if arguments evaluate to true, then the value of the else argument is returned.


2 Answers

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.

like image 109
Karsten W. Avatar answered Oct 18 '22 14:10

Karsten W.


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
like image 36
Metrics Avatar answered Oct 18 '22 16:10

Metrics