10

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 ?

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Wicelo
  • 2,358
  • 2
  • 28
  • 44

2 Answers2

15

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.

Karsten W.
  • 17,826
  • 11
  • 69
  • 103
10

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
Metrics
  • 15,172
  • 7
  • 54
  • 83
  • this is super interesting. i might actually consider it a disadvantage, preferring to get a warning if I try to compare an int and list – 3pitt Oct 19 '17 at 17:55