La valutazione della condition
portato in qualcosa che R non poteva interpretare come logico. È possibile riprodurre questo con, per esempio,
if("not logical") {}
Error in if ("not logical") { : argument is not interpretable as logical
In if
e while
condizioni, R interpreterà zero come FALSE
e non-zero numeri come TRUE
.
if(1)
{
"1 was interpreted as TRUE"
}
## [1] "1 was interpreted as TRUE"
Questo è pericoloso tuttavia, poiché i calcoli che restituiscono NaN
causa questo errore.
if(sqrt(-1)) {}
## Error in if (sqrt(-1)) { : argument is not interpretable as logical
## In addition: Warning message:
## In sqrt(-1) : NaNs produced
E 'meglio passare sempre un valore logico come if
o while
condizionale. Questo di solito significa un'espressione che include uno comparison operator (==
, ecc.) O logical operator (&&
, ecc.).
Utilizzando isTRUE
a volte può essere utile per prevenire questo tipo di errore, ma di notare che, per esempio, è isTRUE(NaN)
FALSE
, che può o non può essere quello che vuoi.
if(isTRUE(NaN))
{
"isTRUE(NaN) was interpreted as TRUE"
} else
{
"isTRUE(NaN) was interpreted as FALSE"
}
## [1] "isTRUE(NaN) was interpreted as FALSE"
Analogamente, le stringhe "TRUE"
/"true"
/"T"
, e "FALSE"
/"false"
/"F"
possono essere utilizzati come condizioni logiche.
Ancora, questo è un po 'pericoloso perché altre stringhe causano l'errore.
if("TRue") {}
Error in if ("TRue") { : argument is not interpretable as logical
Vedere anche i relativi errori:
Error in if/while (condition) { : argument is of length zero
Error in if/while (condition) {: missing Value where TRUE/FALSE needed
if (NULL) {}
## Error in if (NULL) { : argument is of length zero
if (NA) {}
## Error: missing value where TRUE/FALSE needed
if (c(TRUE, FALSE)) {}
## Warning message:
## the condition has length > 1 and only the first element will be used
Accidenti! Fino a quando ho visto il tag 'r-faq' lì, ho temuto che avessi improvvisamente perso il 99% della tua materia grigia :-) –