发布于 2016-01-02 09:41:03 | 483 次阅读 | 评论: 0 | 来源: 网络整理
二进制文件是包含只存储在比特和字节形式的信息的文件(0和1)。它们不是人类可读,将它的字节转换为包含许多其他非打印字符的字符和符号。尝试读取使用任何文本编辑器会显示类似 Ø 和 ð 字符的二进制文件。二进制文件必须由特定程序读取使用。例如,一个微软Word程序的二进制文件只能由Word程序来读取以人类可读形式。这表明,除人类可读文本,有更大量的字符像和页码等的格式信息,其也一起存储字母数字字符。最后一个二进制文件是连续的字节序列。 我们在一个文本文件中看到的断点是一个字符加入第一行到下一个!
有时需要由其他程序所产生的数据,也可以由R为二进制文件进行处理。R语言必需创建可以与其他程序所共享的二进制文件。
R具有两个函数 WriteBin()和 readBin()创建和读取二进制文件。
writeBin(object, con)
readBin(con, what, n )
以下是所使用的参数的说明:
我们考虑R内置数据 "mtcars". 首先,我们从它来创建一个CSV文件,并将其转换为二进制文件并将其保存为一个OS文件。接下来,我们将创建的这个二进制文件读取到R中
我们读出的数据帧 "mtcars" 作为一个 CSV 文件,然后把它写为二进制文件到操作系统。
# Read the "mtcars" data frame as a csv file and store only the columns "cyl","am" and "gear".
write.table(mtcars, file = "mtcars.csv",row.names=FALSE, na="",col.names=TRUE, sep=",")
# Store 5 records from the csv file as a new data frame.
new.mtcars <- read.table("mtcars.csv",sep=",",header=TRUE,nrows = 5)
# Create a connection object to write the binary file using mode "wb".
write.filename = file("/web/com/binmtcars.dat", "wb")
# Write the column names of the data frame to the connection object.
writeBin(colnames(new.mtcars), write.filename)
# Write the records in each of the column to the file.
writeBin(c(new.mtcars$cyl,new.mtcars$am,new.mtcars$gear), write.filename)
# Close the file for writing so that it can be read by other program.
close(write.filename)
上述存储二进制文件创建的所有数据连续字节。因此我们将通过选择的列名的适当的值,以及读取它的列值。
# Create a connection object to read the file in binary mode using "rb".
read.filename <- file("/web/com/binmtcars.dat", "rb")
# First read the column names. n=3 as we have 3 columns.
column.names <- readBin(read.filename, character(), n = 3)
# Next read the column values. n=18 as we have 3 column names and 15 values.
read.filename <- file("/web/com/binmtcars.dat", "rb")
bindata <- readBin(read.filename, integer(), n = 18)
# Print the data.
print(bindata)
# Read the values from 4th byte to 8th byte which represents "cyl".
cyldata = bindata[4:8]
print(cyldata)
# Read the values form 9th byte to 13th byte which represents "am".
amdata = bindata[9:13]
print(amdata)
# Read the values form 9th byte to 13th byte which represents "gear".
geardata = bindata[14:18]
print(geardata)
# Combine all the read values to a dat frame.
finaldata = cbind(cyldata, amdata, geardata)
colnames(finaldata) = column.names
print(finaldata)
当我们上面的代码执行,它会产生以下结果及图表:
[1] 7108963 1728081249 7496037 6 6 4
[7] 6 8 1 1 1 0
[13] 0 4 4 4 3 3
[1] 6 6 4 6 8
[1] 1 1 1 0 0
[1] 4 4 4 3 3
cyl am gear
[1,] 6 1 4
[2,] 6 1 4
[3,] 4 1 4
[4,] 6 0 3
[5,] 8 0 3
我们可以看到,我们从二进制文件得到原始数据回来到R中