【发布时间】:2019-11-27 02:38:26
【问题描述】:
似乎一个数字的as.character() 仍然是一个数字,我觉得这有悖常理。考虑这个例子:
1 > "2"
[1] FALSE
2 > "1"
[1] TRUE
即使我尝试使用as.character() 或paste()
as.character(2)
[1] "2"
as.character(2) > 1
[1] TRUE
as.character(2) < 1
[1] FALSE
这是为什么呢?当我将数字与字符串进行比较时,我不能让 R 返回错误吗?
【问题讨论】:
-
as.character 表示 15 位有效数字的实数和复数 expression?你的最终目标是什么?
-
@NelsonGon 这种行为在冗长的函数中造成了一些问题。我没想到数字和字符之间的比较会引发错误,但没有。
-
这可能回答了stackoverflow.com/questions/14932015/why-true-true-is-true-in-r的问题,重要的部分是
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" > 11。这样做的原因与paste0("A", 1)或1L + 0.1的工作原理基本相同。 R 在需要时更改类型。 -
@NelsonGon
as.character当然会创建字符。然后发生的是>将数字强制转换为character,并且这些字符根据文档说明的整理顺序进行比较。
标签: r