1

Just like the title says, why does "1" == 1 is TRUE? What is the real reason behind this? Is R trying to be kind or is this something else? I was thinking since "1" (or any numbers it really doesn't matter) where read by R as a character it would automatically return FALSE if compare with as.numeric(1) or as.integer(1).

> as.character(1) == as.numeric(1)
[1] TRUE

or

> "1" == 1
[1] TRUE

I guess it is a simple question but I'd like to get an answer. Thank you.

Gainz
  • 1,721
  • 9
  • 24
  • 3
    It is because of type coercsion. You ca check with `identical` `identical(as.character(1), as.numeric(1)) [1] FALSE` which also checks the type – akrun May 17 '19 at 15:50
  • 2
    `all.equal(as.character(1), as.numeric(1))` catches the difference. – s_baldur May 17 '19 at 15:50
  • @akrun Thank you. I see, so R try to coerce the object to a different type so it can "work". sindri gotcha, thanks to you. – Gainz May 17 '19 at 15:51

1 Answers1

5

According to ?==

For numerical and complex values, remember == and != do not allow for the finite representation of fractions, nor for rounding error. Using all.equal with identical is almost always preferable. S

In another paragraph, it is also written

x, y
atomic vectors, symbols, calls, or other objects for which methods have been written. 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.

identical(as.character(1), as.numeric(1))
#[1] FALSE
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Alright, thank you akrun I wasn't aware of this. I'll accept the answer when stack will allow it! – Gainz May 17 '19 at 15:53