Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why TRUE == "TRUE" is TRUE in R?

People also ask

How do you know if a statement is true in R?

isTRUE() function in R Language is used to check whether a value or a logical expression is true or not.

What does true mean in R?

In R, true values are designated with TRUE, and false values with FALSE. When you index a vector with a logical vector, R will return values of the vector for which the indexing vector is TRUE.

Is true and == true Python?

If you don't know the types of your variables, you may want to refactor your code. But if you really need to be sure it is exactly True and nothing else, use is . Using == will give you 1 == True .

What does true/false mean in R?

TRUE and FALSE are reserved words denoting logical constants in the R language, whereas T and F are global variables whose initial values set to these. All four are logical(1) vectors.


According to the help file ?`==` :

If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being character, complex, numeric, integer, logical and raw.

So TRUE is coerced to "TRUE" (i. e. as.character(TRUE)), hence the equality.

The equivalent of an operator === in some other language (i. e. are the two objects equal and of the same type) would be function identical:

identical(TRUE, "TRUE")
[1] FALSE

TRUE and FALSE are reserved words in R. I don't think eznme was correct (before his edit) when he said any non-zero value was TRUE, since TRUE == "A" evaluates to FALSE. (That would have been correct in explaining why TRUE == 1 evaluates to TRUE, but it would not explain the result for TRUE == 7

The explanation given by plannapus was taken out of the context of describing the behavior of as.logical. It is closer to the "truth", because it is the implicit coercion of TRUE to character by the == operator that creates this result. Although T and F are initially given the values of TRUE and FALSE, they can be reassigned to other values or types.

> TRUE == as.logical( c("TRUE", "T", "true", "True") )
[1] TRUE TRUE TRUE TRUE

>  TRUE == 7
[1] FALSE
> TRUE == as.logical(7)
[1] TRUE
>  TRUE == as.logical("A")
[1] NA

(I earlier incorrectly wrote that the coercion induced by TRUE == "TRUE" was to logical; it's actually via as.character(TRUE) returning "TRUE".)


In addition to

TRUE == "TRUE"

these are also true:

  • TRUE==1
  • TRUE==1.0
  • TRUE==1.0000000000000001
  • TRUE==0.99999999999999999 etc, in general also all values close enough to 1.0 to be IEEE754-rounded to it.

But what is more interesing is what if() checks: it checks non-false; in fact this plots!:

if(4.0) plot(1) 

I think the only values that dont trigger if() are 0, F, FALSE and "FALSE" they seem defined as exactly 0.