【问题标题】:In R, why does is.integer(1) return FALSE?在 R 中,为什么 is.integer(1) 返回 FALSE?
【发布时间】: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


【解决方案1】:

希望这有助于澄清一些事情。你的例子不一定 说出全部真相。其实seq返回的向量类型取决于 您使用哪些论据。以下是来自的示例设置 ?seq.

seqList <- list(
    fromto = seq(from = 1, to = 5),
    fromtoby = seq(from = 1, to = 5, by = 1),
    fromtolengthout = seq(from = 1, to = 5, length.out = 5),
    alongwith = seq(along.with = 5),
    from = seq(from = 1),
    lengthout = seq(length.out = 5),
    binary = 1:5
)

通过结果,我们可以看到,当我们使用 by 参数时(如您所做的那样), 结果不是整数类型。一旦发生参数检查,结果的类型就会更改为数字(我想,如果我错了,请纠正我)。

str(seqList)
# List of 7
#  $ fromto         : int [1:5] 1 2 3 4 5
#  $ fromtoby       : num [1:5] 1 2 3 4 5
#  $ fromtolengthout: num [1:5] 1 2 3 4 5
#  $ alongwith      : int 1
#  $ from           : int 1
#  $ lengthout      : int [1:5] 1 2 3 4 5
#  $ binary         : int [1:5] 1 2 3 4 5

seq 是一个通用函数,它根据提供的参数分派给不同的方法。这一切都在?seq 中进行了解释。值得一读。还有seq.intseq_lenseq_along,它们也不同于seq。现在参考您的问题

要确定 x1 是否包含整数值,我需要使用 all(as.integer(x1)==x1)。有没有更简单的方法?

该检查可能会导致一些问题,因为因子也是整数

f <- factor(letters[1:5])
x <- 1:5
f == x
# [1] FALSE FALSE FALSE FALSE FALSE
as.integer(f) == x
# [1] TRUE TRUE TRUE TRUE TRUE

我会选择inheritstypeof。第一个返回一个逻辑,它可以在if 语句中很好地工作。而typeof返回一个向量类型的字符串。

look <- function(x) {
    c(class = class(x), typeof = typeof(x), 
      mode = mode(x), inherits = inherits(x, "integer"))
}
noquote(do.call(rbind, lapply(seqList, look)))
#                 class   typeof  mode    inherits
# fromto          integer integer numeric TRUE    
# fromtoby        numeric double  numeric FALSE   
# fromtolengthout numeric double  numeric FALSE   
# alongwith       integer integer numeric TRUE    
# from            integer integer numeric TRUE    
# lengthout       integer integer numeric TRUE    
# binary          integer integer numeric TRUE    

阅读帮助文件非常有用。我绝对不是这方面的专家,所以如果我在这里有任何问题,请告诉我。这里还有一些更能激发好奇心的东西:

is.integer(1)
# [1] FALSE
is.integer(1L)
# [1] TRUE

【讨论】:

    猜你喜欢
    • 2013-02-25
    • 1970-01-01
    • 2014-07-03
    • 2014-12-29
    • 2018-01-31
    • 1970-01-01
    • 2023-01-16
    • 2019-01-09
    • 2012-07-09
    相关资源
    最近更新 更多