【问题标题】:A problem on "identical()" function in R? How does "identical()" work for different types of objects?R中的“相同()”函数有问题吗? “相同()”如何适用于不同类型的对象?
【发布时间】:2019-10-09 20:17:56
【问题描述】:

(添加了可重现的示例)

我无法理解为什么以下是FALSE(我知道它们分别是doubleinteger):

identical(1, as.integer(1)) # FALSE

?identical 透露:

num.eq: 逻辑指示是否应该使用 == ('equal') 或按位比较来比较(双精度和非 NA 复数)数字。后者(非默认) 区分 -0 和 +0。

sprintf("%.8190f", as.integer(1))sprintf("%.8190f", 1) 返回完全相等位模式。所以,我认为以下至少一项必须返回TRUE。但是,我在以下各项中都得到了FALSE

identical(1, as.integer(1), num.eq=TRUE) # FALSE
identical(1, as.integer(1), num.eq=FALSE) # FALSE

我现在这样考虑:如果sprintf 是符号指示符,而不是存储指示符,那么这意味着identical() 基于存储进行比较。 IE。 identical(bitpattern1, bitpattern1bitpattern2) 返回FALSE。对于上述FALSE/FALSE情况,我找不到任何其他合乎逻辑的解释。

我知道在 R 的 32 位/64 位架构中,整数都存储为 32 位。

【问题讨论】:

  • identical(1, as.numeric("1")) 产生TRUE。这可能是一个起点。另外,identical(1L, as.integer("1")) 也是TRUE
  • @Kots 在两个相同的(...)中,您正在比较相同的东西:“double1 vs double1”和“integer1 vs integer1”。在我的问题中,比较了“double1 vs integer1”。
  • 那我猜你有答案了

标签: r integer double storage notation


【解决方案1】:

它们并不完全相同,因为它们具有不同的类型。如果您查看identical 的文档,您会找到带有注释## FALSE, stored as different types 的示例identical(1, as.integer(1))。这是一个线索。 R language definition 提醒我们:

单个数字,例如 4.2,和字符串,例如“四点二”,仍然是长度为 1 的向量; 没有更多的基本类型(强调我的)。

所以,基本上一切都是带有类型的向量(这也是为什么每次 R 返回时都会出现[1])。您可以通过使用 vector 显式创建长度为 1 的向量,然后将其与 0 进行比较来检查这一点:

x <- vector("double", 1)
identical(x, 0)
# [1] TRUE

也就是说,vector("double", 1)0 都输出类型为“double”且长度 == 1 的向量。

typeofstorage.mode 指向同一个东西,所以当你说“这意味着 identical() 基于存储进行比较”时,你是对的。我认为这不一定意味着正在比较“位模式”,尽管我认为这是可能的。查看使用storage.mode 更改存储模式时会发生什么:

## Assign integer to x. This is really a vector length == 1.
x <- 1L

typeof(x)
# [1] "integer"

identical(x, 1L)
# [1] TRUE

## Now change the storage mode and compare again. 
storage.mode(x) <- "double"

typeof(x)
# [1] "double"

identical(x, 1L) # This is no longer TRUE.
# [1] FALSE

identical(x, 1.0) # But this is.
# [1] TRUE

最后一点:identical 的文档指出 num.eq 是一个……

逻辑指示是否应该使用 == ('equal') 或按位比较来比较(双精度和非 NA 复数)数字。

因此,更改num.eq 不会影响任何涉及整数的比较。请尝试以下操作:

# Comparing integers with integers.
identical(+0L, -0L, num.eq = T) # TRUE
identical(+0L, -0L, num.eq = F) # TRUE

# Comparing integers with doubles.
identical(+0, -0L, num.eq = T) # FALSE
identical(+0, -0L, num.eq = F) # FALSE

# Comparing doubles with doubles.
identical(+0.0, -0.0, num.eq = T) # TRUE
identical(+0.0, -0.0, num.eq = F) # FALSE

【讨论】:

  • 非常感谢。你系统地解释了我想要的一切。
猜你喜欢
  • 1970-01-01
  • 2013-06-01
  • 2020-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-11-21
  • 2013-02-17
  • 1970-01-01
  • 2016-09-26
相关资源
最近更新 更多