将数组写入R

时间:2017-04-21 11:13:26

标签: arrays r binaryfiles

Hei,我正在尝试将R中的三维数组写入.bin文件,以便稍后从FORTRAN调用它。

我使用以下方法:

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来保留对象结构吗?

1 个答案:

答案 0 :(得分:0)

二进制数据没有&#34;结构&#34;。如果希望对象的结构位于二进制数据中,则需要手动添加内容。例如,您可以在文件的开头添加一些数据。

第一个数字是维度数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中分配结构并读取剩余数据以填充所有元素。