【发布时间】:2014-11-04 21:57:41
【问题描述】:
在 R 中,is.integer(1) 返回 FALSE,class(1) 返回“数字”,而is.integer(1:1) 返回 TRUE,class(1:1) 返回“整数”。为什么is.integer(1) 不返回 TRUE?
将打印的值与 class() 或 typeof() 的输出进行比较会导致反直觉的结果。例如
x1=seq(from=1, to=5, by=1)
x2=1:5
x1
[1] 1 2 3 4 5
x2
[1] 1 2 3 4 5
class(x1)
[1] "numeric"
class(x2)
[1] "integer"
要确定 x1 是否包含整数值,我需要使用 all(as.integer(x1)==x1)。有没有更简单的方法?
class() 可以返回一个数组,例如有序因子。 class(1) 不应该返回 c("numeric", "integer") 吗?
【问题讨论】:
-
数字在 R 中默认被视为
numeric。尝试x <- 1L强制integer。 -
另见
?is.integer中的“注释”和“示例” -
这可能是 stackoverflow.com/questions/3476782/… 的副本,但您在这里问两个问题:(1)“是否有更简单的方法来测试整数值”? (以前的重复)和(2)“不应该
class(1)返回c("numeric","integer")?” (部分由@jlhoward 现已删除的答案解决)
标签: r types integer numeric type-conversion