Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing integers with characters in R [duplicate]

Tags:

r

It appears that as.character() of a number is still a number, which I find counter intuitive. Consider this example:

1 > "2"
[1] FALSE
2 > "1"
[1] TRUE

Even if I try to use as.character() or paste()

as.character(2)
[1] "2"
as.character(2) > 1
[1] TRUE
as.character(2) < 1
[1] FALSE

Why is that? Can't I have R return an error when I am comparing numbers with strings?

like image 365
Masood Sadat Avatar asked Nov 26 '25 18:11

Masood Sadat


1 Answers

The documentation of ?Comparison 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.

So in your case the number is automatically coerced to string and the comparison is made based on the respective collation.

In order to prevent it, the only option I know of is to manually compare the class first.

like image 155
AEF Avatar answered Nov 29 '25 08:11

AEF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!