0

R uses rules of implicit coercion to convert values across data types, and this also applies to character vectors (link to manual, link to Advanced R). The documentation (available at ?==``) also states that:

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.

This means that more complex types as the character type will prevail over simpler types as logical or integer.

However, I still have issues with this, and I just had counter-intuitive coercion from character to numeric type that I would like to understand: why is "4" > 10 evaluating TRUE? I also note that "4" > 5 evaluates FALSE, and "4" > 3 is TRUE, which actually leads to expect that coercion is converting "4" (character) to 4 (integer).

I was hesitant to post this basic question, but my search could not find any question explain this form of implicit coercion (e.g., this and this questions only involve the equality operator).

Can you explain this behavior? And can you point me to a list of the exact rules of implicit coercion?

000andy8484
  • 563
  • 3
  • 16
  • 2
    This is covered in section 8.1.9 of the R Inferno, though there's not much explantation except "don't compare coerced values" – Bill O'Brien Jul 22 '21 at 14:40
  • 2
    `"4" > 10` is actually compared as `"4" > "1"`. Similar question was asked yesterday https://stackoverflow.com/questions/68454522/why-do-i-get-true-when-checking-if-a-character-value-is-greater-than-a-number – Ronak Shah Jul 22 '21 at 14:41
  • 1
    See also the 'Details' section of `?Comparison` for some explanation. – Jaap Jul 22 '21 at 14:43

0 Answers0