R教程

R 二进制文件

二进制文件是包含仅以位和字节(0 和 1)形式存储的信息的文件。它们不是人类可读的,因为其中的字节转换为包含许多其他不可打印字符的字符和符号。尝试使用任何文本编辑器读取二进制文件都会显示 Ø 和 ð 等字符。
二进制文件必须由特定程序读取才能使用。例如,Microsoft Word 程序的二进制文件只能由 Word 程序读取为人类可读的形式。这表明,除了人类可读的文本之外,还有更多信息,如字符格式和页码等,这些信息也与字母数字字符一起存储。最后一个二进制文件是一个连续的字节序列。我们在文本文件中看到的换行符是连接第一行和下一行的字符。
有时,其他程序生成的数据需要R作为二进制文件进行处理。还需要 R 来创建可以与其他程序共享的二进制文件。
R 有两个函数 WriteBin()readBin() 来创建和读取二进制文件。

语法

writeBin(object, con)
readBin(con, what, n )
以下是所用参数的说明-
con 是读取或写入二进制文件的连接对象。 object 是要写入的二进制文件。 什么是表示要读取的字节的字符、整数等模式。 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 中的二进制文件取回了原始数据。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4