将二进制文件读入R

4

我想将一个二进制文件读入R,但是这个文件的数据行是以二进制代码写入的。因此,它没有一个完整的数据集属于一个列,而是存储为数据行。以下是我的数据样式:

Bytes 1-4:            int        ID
Byte 5:               char       response character
Bytes 6-9:            int        Resp Dollars
Byte 10:              char       Type char

有人能帮我解决如何将这个文件读入R的问题吗?

以下是我到目前为止尝试过的代码。我尝试了几种方法,但效果有限。不幸的是,我不能在公共网站上发布任何数据,抱歉。我相对来说是R的新手,所以需要一些帮助来改进代码。

> binfile = file("File Location", "rb")
> IDvals = readBin(binfile, integer(), size=4, endian = "little")
> Responsevals = readBin(binfile, character (), size = 5)
> ResponseDollarsvals = readBin (binfile, integer (), size = 9, endian= "little")
Error in readBin(binfile, integer(), size = 9, endian = "little") : 
  size 9 is unknown on this machine
> Typevals = readBin (binfile, character (), size=4)
> binfile1= cbind(IDvals, Responsevals, ResponseDollarsvals, Typevals)
> dimnames(binfile1)[[2]]
[1] "IDvals"            "Responsevals"        "ResponseDollarsvals" "Typevals"  

> colnames(binfile1)=binfile
Error in `colnames<-`(`*tmp*`, value = 4L) : 
  length of 'dimnames' [2] not equal to array extent

2
你能发布数据文件的前几行吗? - user399470
使用readBin函数读取原始字节,将其推入行数与文件相同的矩阵中,然后从列集合中读取readBin。这很快。对于更复杂的格式,可以通过删除所有标题内容并快速读取来实现:https://dev59.com/HmnWa4cB1Zd3GeqP3LS8 - mdsumner
提供文件,我会组合一个示例。 - mdsumner
mdsumner - 我无法分享数据文件,因为公司有保密协议 - 你能否发布简化版本的代码?我对R相对较新,所以在跟随您发布的链接中遇到了一些困难....谢谢! - user1819654
我不想做的事情是生成测试文件,这也是你问题的问题所在。 - mdsumner
1个回答

7
你可以将文件打开为原始文件,然后使用readBin或readChar命令获取每一行。在进行操作时,将每个值添加到列中。
my.file <- file('path', 'rb')

id <- integer(0)
response <- character(0)
...

循环执行此代码块:
id = c(id, readBin(my.file, integer(), size = 4, endian = 'little'))
response = c(response, readChar(my.file, 1))
...
readChar(my.file, size = 1) # For UNIX newlines.  Use size = 2 for Windows newlines.

然后创建你的数据框架。
参见这里:http://www.ats.ucla.edu/stat/r/faq/read_binary.htm

嗨,Matthew - 我正在尝试跟随你的代码,但想知道如何确定我的文件是否有UNIX或Windows换行?谢谢! - user1819654
这是一些你需要了解的东西,基于你如何编写文件。你可以通过查看二进制数据来确定。如果你在UNIX系统上,命令'od-t x1<file>'将打印字节值。单个'0a'作为行终止符表示UNIX行结尾。一对“0d”和“0a”表示Windows行结尾。一个记录与下一个之间没有间隔表示没有行结尾,并且您不应使用额外的readChar()调用来吸收(不存在的)结束字符。 - Matthew Lundberg
Matthew - 我已经弄清楚了Windows的行尾符 - 最后一个问题 - 我正在尝试找出响应美元列正确的字节大小 - 每次我尝试输入字节大小时,都会出现错误提示,说这台机器上不知道该大小 - 我尝试了以下字节大小 - 6、9、3、4、5 - 先感谢你的帮助。 - user1819654

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接