Ciò accade perché ifelse
restituirà sempre un valore. Quando si esegue ifelse(1<2,print("true"),print("false"))
, viene selezionata la condizione yes
. Questa condizione è una chiamata alla funzione per stampare "true"
sulla console, e così fa.
Ma la funzione print()
restituisce anche il suo argomento, ma in modo invisibile (ad esempio i compiti, ad esempio), altrimenti in alcuni casi il valore verrà stampato due volte. Quando viene valutata l'espressione yes
, il risultato è ciò che restituisce ifelse
e ifelse
non restituisce in modo invisibile, quindi stampa il risultato, poiché è stato eseguito nell'ambiente globale e senza assegnazione.
Possiamo testare alcune variazioni e verificare cosa sta succedendo.
> result <- print("true")
[1] "true" # Prints because the print() function was called.
> result
[1] "true" # The print function return its argument, which was assigned to the variable.
> ifelse(1<2, {print("true");"TRUE"},print("false"))
[1] "true" #This was printed because print() was called
[1] "TRUE" #This was printed because it was the value returned from the yes argument
Se assegniamo questa ifelse()
> result <- ifelse(1<2, {print("true");"TRUE"},print("false"))
[1] "true"
> result
[1] "TRUE"
Possiamo anche guardare il caso in cui entrambe le condizioni condizioni vengono valutate:
> ifelse(c(1,3)<2, {print("true");"TRUE"},{print("false");"FALSE"})
[1] "true" # The yes argument prints this
[1] "false" # The no argument prints this
[1] "TRUE" "FALSE" # This is the returned output from ifelse()
si dovrebbe usare ifelse
per creare un nuovo oggetto, non eseguire azioni in base a una condizione. Per questo, utilizzare if
else
. The R Inferno ha una buona sezione (3.2) sulla differenza tra i due.
probabilmente correlate al [questo] (http://stackoverflow.com/questions/16275149/does-ifelse-really-calculate-both-of-its- vettori in ogni-tempo-è-da-lento/16.275.201 # 16.275.201). – MichaelChirico
nota anche che 'ifelse' è progettato per essere applicato ai vettori, non agli scalari, quindi forse stai meglio usando' if (1 <2) print ("true") else print ("false") 'comunque. – MichaelChirico
E nota che se lo assegni, come 'z <- ifelse (1 <2, print (" true "), print (" false "))', il nuovo oggetto manterrà il risultato corretto. – ulfelder