[英]How to save a numerical matrix and restore it accurately?
我想保存一个数值矩阵,然后准确地恢复它。 但是,如果我使用 identical() 来比较保存前和保存后的矩阵,它们并不相同。 我猜这个问题是由浮点精度问题引起的。 我怎样才能使两个矩阵相同?
谢谢!
options(digits = 10)
data <-
c(1 / 11, 1 / 22, 1 / 33, 1 / 44, 1 / 55, 1 / 66, 1 / 77, 1 / 88, 1 / 99) # Generate a numerical matrix.
x <- matrix(data,
nrow = 3,
ncol = 3,
byrow = TRUE)
write.table(x, "test.csv") # Save the matrix.
y <- as.matrix(read.table("test.csv")) # Restore the matrix.
y <- unname(y) # Remove the attributes.
all.equal(x, y) # I got TRUE.
identical(x, y) # I got FALSE. How can I get TRUE here?
unlink("test.csv")
all.equal
有一个 tolerance 参数,其默认值允许比较的值非常接近相等但不完全相等,而identical
需要完全相等。
如果您希望恢复的文件相同,您可以另存为 RDS 而不是 csv。另存为 RDS 还保留了 R object 的其他属性,而另存为 csv 则不会,这样您就可以避免转换 object读入后返回所需的类型。
options(digits = 10)
data <-
c(1 / 11, 1 / 22, 1 / 33, 1 / 44, 1 / 55, 1 / 66, 1 / 77, 1 / 88, 1 / 99) # Generate a numerical matrix.
x <- matrix(data,
nrow = 3,
ncol = 3,
byrow = TRUE)
saveRDS(x, "test.RDS")
y <- readRDS( "test.RDS") # Restore the matrix.
all.equal(x, y)
#> [1] TRUE
identical(x, y)
#> [1] TRUE
unlink("test.RDS")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.