简体   繁体   English

如何保存一个数值矩阵并准确还原?

[英]How to save a numerical matrix and restore it accurately?

I want to save a numerical matrix and then restore it accurately.我想保存一个数值矩阵,然后准确地恢复它。 But if I use identical() to compare the before- and after-saved matrices, they are not identical.但是,如果我使用 identical() 来比较保存前和保存后的矩阵,它们并不相同。 I guess the problem is caused by floating point precision issues.我猜这个问题是由浮点精度问题引起的。 How can I make the two matrices identical?我怎样才能使两个矩阵相同?

Thanks!谢谢!

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 has a tolerance parameter whose default allows for the values being compared to be very near equal but not exactly so while identical requires exact equality. all.equal有一个 tolerance 参数,其默认值允许比较的值非常接近相等但不完全相等,而identical需要完全相等。

If you'd like the restored file to be identical, you can save as an RDS rather than a csv. Saving as an RDS also preserved other attributes of an R object that saving as a csv does not, allowing you to avoid converting the object back to the desired type after read in.如果您希望恢复的文件相同,您可以另存为 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM