将二进制文件读入R [英] Reading binary file into R

查看:100
本文介绍了将二进制文件读入R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个二进制文件读入R,但是该文件具有用二进制代码编写的数据行.因此,它没有属于一列的一组完整数据,而是将其存储为数据行.这是我的数据:

I'm trying to read a binary file into R but this file has rows of data written in binary code. So it doesnt have one full set of data belonging to one column instead it is stored as rows of data. Here's what my data looks like:

字节1-4:int ID 字节5:char响应字符 字节6-9:int resp Dollars 字节10:char类型char

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

任何人都可以帮助我弄清楚如何将此文件读入R吗?

anyone can help me figure out how to read this file into R?

伙计们,

这是我到目前为止尝试过的代码.我尝试了几件事,但收效甚微.不幸的是,我无法将任何数据发布在公共网站上,对此表示歉意.我是R的新手,因此在如何改进代码方面需要一些帮助.提前致谢.

Here's the code ive tried so far. I tried a couple of things with limited success. Unfortunately, I cant post any of the data on public sites, apologies. I’m relatively new to R, so I need some help in terms of how to improve the code. Thanks in advance.

> 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

推荐答案

您可以将文件作为原始文件打开,然后发出readBin或readChar命令以获取每一行.随便将每个值添加到列中.

You could open the file as a raw file, then issue readBin or readChar commands to get each line. Append each value to a column as you go.

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

这篇关于将二进制文件读入R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆