3

I have a string and while comparing with number it does not break and say that this is positive, any hints why this happens?

x <- "The day is bad, I don't like anything! I feel bad and sad really sad"
if (x == 0) {
   print("x is equal to 0")
}else if (x > 0) {
   print("x is positive")
}else if (x < 0 ){
   print("x is negative")
}

The result is:

"x is positive"
Joni Hoppen
  • 658
  • 5
  • 23
  • 2
    You have a string 'x', then you are doing the comparison with `x == 0` Have you missed any code – akrun May 25 '19 at 18:59
  • 2
    It could be a result of the ASCII code where the values would be greater than number 0. For e.g. `letters > 0` – akrun May 25 '19 at 19:04
  • The ideia is to see if the code would eventually break. It is a bit confusing and I see potential problems where this comparisons should't occur. – Joni Hoppen May 25 '19 at 19:06

1 Answers1

8
?'>'

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

So while you compare x which is character vector, to 0, that is numeric type, former is converted to character '0':

  • x == 0 evaluates to FALSE because "The day is bad..." != "0";
  • x < 0 evaluates to FALSE because while ordered, 0 is placed before "The day is bad..." :

...Comparison of strings in character vectors is lexicographic within the strings using the collating sequence of the locale in use...

sort(c(x, 0))
#[1] "0"                                                                   
#[2] "The day is bad, I don't like anything! I feel bad and sad really sad"

Meaning that x is thought as greater than '0' because of the lexicographic order.

  • Finally x > 0 evaluates to TRUE because '0' precedes 'The day is bad, I dont...' and your code returns [1] x is positive

And if, trying to prove our hypothesis, we ask ourselves, whether Chuck Norris is able to beat the Infinity, we find that it is not the case:

'Chuck Norris' > Inf
# [1] FALSE

In contrast, Keith Richards, as anybody would expect, have no problem with that:

'Keith Richards' > Inf
# [1] TRUE
utubun
  • 4,400
  • 1
  • 14
  • 17