2017-04-21 106 views
1

嘿,我正在嘗試在R中寫入一個3維數組到一個.bin文件,以便稍後從FORTRAN中調用它。將數組寫入.bin文件中R

我使用下面的方法:

my.array <- array(1:36, dim=c(3,4,3)) 

zz <- file("new.bin", "wb") 
writeBin (my.array,zz, size = 8) 
close(zz) 

但這產生了錯誤消息:

Error in writeBin(my.array, zz, size = 8) : can only write vector objects 

我認爲,如果我拼合陣列的向量作爲在

writeBin (as.vector(my.array),zz, size = 8) 

writeBin運行時沒有錯誤消息,我能夠將文件讀取到FORTRAN(請參閱How to write .bin file in R and open it in Fortran

但是,我有興趣保留對象的結構,因爲我將使用巨大的數組。

無論如何寫在R中保存對象結構的.bin。

回答

0

二進制數據沒有「結構」。如果你想讓對象的結構在二進制數據中,你需要手動添加一些東西。例如,您可以在文件的開頭添加一些數據。

第一個數字是維數D.然後下一個D數將是每個維數的大小。其餘的字節是數據。

所以,你的例子看起來是這樣的:

writeBin(c(length(dim(my.array)), dim(my.array), my.array), raw(), size = 8) 
    [1] 03 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 04 00 00 00 00 00 00 00 03 
[26] 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 03 00 
[51] 00 00 00 00 00 00 04 00 00 00 00 00 00 00 05 00 00 00 00 00 00 00 06 00 00 
[76] 00 00 00 00 00 07 00 00 00 00 00 00 00 08 00 00 00 00 00 00 00 09 00 00 00 
[101] 00 00 00 00 0a 00 00 00 00 00 00 00 0b 00 00 00 00 00 00 00 0c 00 00 00 00 
[126] 00 00 00 0d 00 00 00 00 00 00 00 0e 00 00 00 00 00 00 00 0f 00 00 00 00 00 
[151] 00 00 10 00 00 00 00 00 00 00 11 00 00 00 00 00 00 00 12 00 00 00 00 00 00 
[176] 00 13 00 00 00 00 00 00 00 14 00 00 00 00 00 00 00 15 00 00 00 00 00 00 00 
[201] 16 00 00 00 00 00 00 00 17 00 00 00 00 00 00 00 18 00 00 00 00 00 00 00 19 
[226] 00 00 00 00 00 00 00 1a 00 00 00 00 00 00 00 1b 00 00 00 00 00 00 00 1c 00 
[251] 00 00 00 00 00 00 1d 00 00 00 00 00 00 00 1e 00 00 00 00 00 00 00 1f 00 00 
[276] 00 00 00 00 00 20 00 00 00 00 00 00 00 21 00 00 00 00 00 00 00 22 00 00 00 
[301] 00 00 00 00 23 00 00 00 00 00 00 00 24 00 00 00 00 00 00 00 

在你的Fortran代碼,你會讀第一個號碼找到維度的總數,D.然後,你會讀下一d號碼找到大小或每個維度。現在您可以在Fortran中分配結構並讀取其餘數據以填充所有元素。

+0

我知道二進制數據是未格式化的。但是據我的理解,你的建議仍然需要在將數組寫入R中的.bin之前將數組平坦化。 – Larusson

+0

是的,你必須先將它轉換成矢量。否則,你會收到一個錯誤,「只能寫矢量對象」。 –