为什么“一"<2 在 R 中等于 FALSE? [英] Why does "one" < 2 equal FALSE in R?

查看:26
本文介绍了为什么“一"<2 在 R 中等于 FALSE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Hadley Wickham 关于强制转换的 Advanced R 部分,我无法理解这种比较的结果:

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

我假设 R 将 2 强制转换为一个字符,但我不明白为什么 R 返回 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

所以我的问题是双重的:首先,为什么这个答案,其次,有没有办法看到 R 如何像这些示例一样转换逻辑向量中的各个元素?

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?

推荐答案

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

所以在这种情况下,数字的优先级低于字符.所以 2 被强制转换为字符 "2".字符向量中字符串的比较是按字典顺序进行的,据我所知,它是按字母顺序排列的,但取决于语言环境.

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.

这篇关于为什么“一"&lt;2 在 R 中等于 FALSE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆