【问题标题】:How is R handling numbers so that they are the same but not indentical() after exporting and re-importing?R如何处理数字,以便在导出和重新导入后它们相同但不相同()?
【发布时间】:2015-03-27 23:06:31
【问题描述】:

A 和 B 应该是同一个数据框。 A 是在 R 中生成的,B 是 A 导出的,然后它们又被导入到 R 中。

两者的尺寸均为 49 x 97,包含第一列字符和所有其他列编号。 str() 分别将它们列为“chr”和“num”。

根据我对数字列的看法,有时 R 会发现它们相同,有时则不同:

> identical(A,B)

FALSE
#The dataframes A and B are not the same

> identical(A[,1],B[,1])

TRUE
#The character-containing columns are the same

> identical(A[,-1],B[,-1])

FALSE
#The number-containing columns are not the same

> identical(matrix(A[,-1]),matrix(B[,-1]))

TRUE
#If the number-containing columns are converted into a matrix, they are the same

> identical(as.matrix(A[,-1]),as.matrix(B[,-1]))

FALSE
> identical(as.matrix(A[1:49,-1]),as.matrix(B[1:49,-1]))

TRUE
#But if they're converted into a matrix using as.matrix() instead of
# matrix() they're only the same if the 49 rows are explicitly indexed

我的问题: R 解释数字的方式有什么不同?
它们有时被视为双精度数,有时被视为浮点数吗? 你怎么知道 R 什么时候会做其中一个,我能确定 A 和 B 真的是一样的吗?


编辑:我在 R 领域又有 2 年经验后的建议:

  • 使用all.equal() 而不是identical() 来查看不同之处的解释并忽略微小的舍入错误
  • 使用saveRDS()readRDS() 以完全相同的格式导出和重新导入(而且速度更快)
  • 请记住,matrix()as.matrix() 的行为可能不同

【问题讨论】:

  • 通过导出它们导入,你的意思是read.table 然后write.table(或它们的变体之一)?如果是这样,它们可能会有所不同,因为文本和二进制值可能不同,但通常不会超过 10^-16。您可以通过检查max(abs(A-B)) 进行测试。如果您希望会话之间的值相同,请使用 readRDSsaveRDS
  • 如果不提供可重现的示例,可能很难回答这个问题。

标签: r import dataframe export number-formatting


【解决方案1】:

请阅读identical 的帮助页面。它应用了一套更严格和更广泛的测试,而不仅仅是检查数字条目是否相同。 R 对象的所有属性(包括名称和非打印属性)都经过身份检查。如果您想检查数值等价物,那么也许您应该首先剥离对象的属性,可能使用as.vector 或类似功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 2018-04-24
    • 2014-06-16
    • 1970-01-01
    • 2016-03-02
    • 2018-08-28
    相关资源
    最近更新 更多