簡體   English   中英

如何保存一個數值矩陣並准確還原?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM