1

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

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.