Mandar Sadye Mandar Sadye - 1 year ago 148
R Question

why is "<integer>" == <integer> true in R

I just started learning R and in my first assignment, I face a problem where I need to compare a bunch of variables and while doing that I am supposed to get false when comparing two variables not only when they are not equal but also when their type is not same.
For example :

7 == "7"


gives true which should be false.
Currently, I am doing the same as follows:

var1 = 8 == "8"
var2 = typeof(8) == typeof("8")
var1 & var2


I guess there should be some much simpler approach for the same.
It seems like it implicitly converting 7 to "7" as it does when we add numeric to a character vector.
So is there a way to get the same result in 1 line?

Answer Source

From the ?Comparison help page:

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.

On the same help page, the authors warn for using == and != for tests in if-expressions. They recommend using identical() instead:

7 == "7"
# TRUE
identical(7, "7")
# FALSE
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download