Perché possiamo usare ifelse()
ma non else if(){}
in with()
o within()
?
Ho sentito che il primo è vectorizable e non il secondo. Cosa significa ?
Il costrutto if
considera solo il primo componente quando viene passato ad esso un vettore (e fornisce un avvertimento)
if(sample(100,10)>50) print("first component greater 50") else print("first component less/equal 50")
La funzione ifelse
esegue il controllo su ciascun componente e restituisce un vettore
ifelse(sample(100,10)>50, "greater 50", "less/equal 50")
La funzione ifelse
è utile per la transform
, ad esempio. È spesso utile usare &
o |
nelle condizioni ifelse
e &&
or ||
in if
.
Rispondi per la tua seconda parte:
* Usando if
quando x ha lunghezza 1 ma quella di y è maggiore di 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
Usando ifelse
quando x ha lunghezza 1 ma quella di y è maggiore di 1
ifelse (x < y,x,y) [1] 4 4 4 3 4