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

  • Why is TRUE == "TRUE" is TRUE in R?
  • Is there an equivalent for === in R?

Update:

They all return FALSE :

 TRUE == "True" TRUE == "true" TRUE == "T" 

The only TRUE value is TRUE == "TRUE" .

In the case of checking with identical() everything works fine.

Second update:

With the === operator, I meant the process of checking the value and data type of a variable. In this case, I assumed that the == operator would only compare the values ​​of the variables, not their data type.

+47
r boolean-logic
Feb 18 '13 at 8:20
source share
3 answers

According to the help file ?`==` :

If two arguments are atomic vectors of different types, one is forced to the type of the other, the (decreasing) order of priority is a symbol, complex, numerical, integer, logical and unprocessed.

So TRUE coerced to "TRUE" (ie as.character(TRUE) ), hence equality.

The equivalent of the === operator (that is, two objects are equal and of the same type) will be the identical function:

 identical(TRUE, "TRUE") [1] FALSE 
+52
Feb 18 '13 at 8:31
source share

TRUE and FALSE are reserved words in R. I do not think eznme was right (before editing it) when he said that any nonzero value was TRUE, since TRUE == "A" evaluates to FALSE. (It would be correct to explain why TRUE == 1 evaluates to TRUE, but does not explain the result for TRUE == 7

The explanation given by plannapus has been inferred from the context of the as.logical behavior as.logical . It is closer to true because it implicitly forces TRUE to a character using the == operator, which creates this result. Although T and F initially set to 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 

(Earlier, I wrote incorrectly that coercion induced by TRUE == "TRUE" was logical: in fact, as.character (TRUE) returns "TRUE".)

+10
February 42-18 '13 at 8:40
source share

In addition to

TRUE == "TRUE"

this is also true:

  • TRUE == 1
  • TRUE == 1.0
  • TRUE == 1.0000000000000001
  • TRUE == +0.99999999999999999, etc., in general, all values ​​close to 1.0 should also be rounded to IEEE754.

But more interesting is the if() check: it checks non-false ; actually these stories !:

 if(4.0) plot(1) 

I think that the only values ​​that do not run if() are 0, F, FALSE and FALSE, they seem to be exactly 0.

+3
Feb 18 2018-12-18T00: 00Z
source share



All Articles