Why does “one” < 2 equal FALSE in R?

醉酒当歌 提交于 2019-11-26 11:35:45

问题


I\'m reading Hadley Wickham\'s Advanced R section on coercion, and I can\'t understand the result of this comparison:

\"one\" < 2
# [1] FALSE

I\'m assuming that R coerces 2 to a character, but I don\'t understand why R returns FALSE instead of returning an error. This is especially puzzling to me since

-1 < \"one\"
# TRUE

So my question is two-fold: first, why this answer, and second, is there a way of seeing how R converts the individual elements within a logical vector like these examples?


回答1:


From help("<"):

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 this case, the numeric is of lower precedence than the character. So 2 is coerced to the character "2". Comparison of strings in character vectors is lexicographic which, as I understand it, is alphabetic but locale-dependent.




回答2:


It coerces 2 into a character, then it does an alphabetical comparison. And numeric characters are assumed to come before alphabetical ones

to get a general idea on the behavior try

'a'<'1'
'1'<'.'
'b'<'B'
'a'<'B'
'A'<'B'
'C'<'B'


来源:https://stackoverflow.com/questions/27005295/why-does-one-2-equal-false-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!