4

Could you elaborate on, what is going on here:

a = "TRUE"
b = TRUE
a
#[1] "TRUE"
b
#[1] TRUE
str(a)
#chr "TRUE"
str(b)
#logi TRUE
a == b
#[1] TRUE

This is only TRUE for the string "TRUE" in that e.g.:

"STRING" == TRUE
#[1] FALSE

So it is not because a non-empty string is TRUE like en e.g. Perl, therefore I would have expected TRUE == "TRUE" would yield FALSE?

LeonDK
  • 142
  • 10
  • 4
    From `?Comparison`: _"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._" – lukeA Jun 04 '15 at 08:04
  • 1
    @lukeA : I see, thank you for your answer. This is imho an annoying feature, I would prefer being punished if I was trying to compare in-comparable entities... – LeonDK Jun 04 '15 at 08:10
  • It is part of a general principle in R that things are promoted to the most general representation when incompatible types are mixed in an operation. I think it fits to the fact that R is a dynamic and functional language, more like Lisp, than the C family. – Mike Wise Jun 04 '15 at 08:17
  • Just a quick-add: It can be exemplified like so: typing `c(1,"1",TRUE,"TRUE")` at the R-prompt will yield: `[1] "1" "1" "TRUE" "TRUE"` – LeonDK Jun 04 '15 at 08:23
  • Shouldn't someone post an answer so the question that can be marked as a solution and be "retired"? – Mike Wise Jun 04 '15 at 08:47
  • R tries to be as accommodating as possible, and programmer should keep that in mind. No need for a whip on every corner. :) – Roman Luštrik Jun 04 '15 at 08:52
  • @lukeA : I think you answered the question nicely, so you should be credited? – LeonDK Jun 04 '15 at 08:53

1 Answers1

5

To quote ?Comparison in the help files:

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.

R is automatically coercing the values down resulting in

"TRUE" == TRUE
# [1] TRUE
1 == TRUE
# [1] TRUE

etc.

lukeA
  • 53,097
  • 5
  • 97
  • 100