我想以二进制格式编写(以后检索)数据。我试图得到一个最小的例子,至少工作到气味测试的水平(读取输入应该看起来像书面输出),但我还没有得到它,并且始终正确。我的机器是一个带有小端的linux,但由于这是常量,我从调用中省略了它。我也不确定在写入中指定size
参数是否更好,或者将其删除。无论如何,加载的输入看起来不像out
:
out<-seq(1,50,2)
##write
write<-file('~/output.txt','wb')
writeBin(out,con=write,size=4)
close(write)
##read
read<-file('~/output.txt','rb')
readBin(con=read,what=numeric(),n=length(out))
# [1] 3.200001e+01 3.276801e+04 1.048576e+06 1.677722e+07 1.006633e+08 4.026532e+08 1.610613e+09 6.442452e+09 1.503239e+10 3.006478e+10 6.012955e+10 1.202591e+11
close(read)
答案 0 :(得分:7)
这是一个有效的例子:
R> dat <- seq(1,50,2)
R> dat
[1] 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
R>
我们只是将对象写入二进制连接 - 省略第三个参数:
R> con <- file("/tmp/foo.bin", "wb")
R> writeBin(dat, con)
R> close(con)
R>
然后可以回读:
R> con <- file("/tmp/foo.bin", "rb")
R> dat2 <- readBin(con, what="numeric", n=length(dat))
R> dat2
[1] 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
R>
R> all.equal(dat, dat2)
[1] TRUE
但是,您需要存储长度。我使用了一种内部文件格式,它首先写入关于行,列,“格式编号”的固定(已知)数量的整数,然后读取/写入总共行* cols数字。我们还将它包装成一个gzip-ed文件连接。
您甚至可以将其概括为在数据框中编写列 - 但如果R是您唯一的读取器/写入器,则通过save()
已经存在的序列化更好。