【发布时间】: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))进行测试。如果您希望会话之间的值相同,请使用readRDS和saveRDS。 -
如果不提供可重现的示例,可能很难回答这个问题。
标签: r import dataframe export number-formatting