Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading