简体   繁体   中英

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 ?

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 .

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

Using ifelse 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM