Why does "some string" > 0 evaluate to TRUE in R?

Advertisements

Why does R evaluate "string" > 0 as TRUE?
I first thought this might be due to an implicit type conversion or that R interprets this as nchar("string") > 0. This does not seem to be the case:

"some string" > 0
#[1] TRUE

# Verify if any other comparison is true:
"some string" < 0
# [1] FALSE
"some string" == 0
#[1] FALSE

# Check for implicit type conversion:
as.numeric("some string")
#[1] NA
as.integer("some string")
# [1] NA
NA == 0
#[1] NA # So this is not what is happening under the hood

# Check if the comparison is translated to nchar(...) > 0:
nchar("some string")
# [1] 11
"some string" > 1000000
#[1] TRUE # The result seems to stay the same for any number!

I found a similar question for PHP but that didn’t help me understand R’s behavior:
Why does "someString" == 0 evaluate to true in PHP

>Solution :

I first thought this might be due to an implicit type conversion

It is!

Just the other way round from what you think. You can check this yourself by forcing a conversion to a common type — e.g. by putting both into a vector:

c("string", 0)
# [1] "string" "0"

So it coerces both arguments to string, and "s" > "0" (the numeric value of the characters are ordered such that all digits appear before all letters).

Leave a ReplyCancel reply