位置:首頁 > 大數據教學 > R語言教學 > R語言處理二進製文件

R語言處理二進製文件

二進製文件是包含隻存儲在比特和字節形式的信息的文件(0和1)。它們不是人類可讀,將它的字節轉換為包含許多其他非打印字符的字符和符號。嘗試讀取使用任何文本編輯器會顯示類似 Ø 和 ð 字符的二進製文件。二進製文件必須由特定程序讀取使用。例如,一個微軟Word程序的二進製文件隻能由Word程序來讀取以人類可讀形式。這表明,除人類可讀文本,有更大量的字符像和頁碼等的格式信息,其也一起存儲字母數字字符。最後一個二進製文件是連續的字節序列。 我們在一個文本文件中看到的斷點是一個字符加入第一行到下一個!

有時需要由其他程序所產生的數據,也可以由R為二進製文件進行處理。R語言必需創建可以與其他程序所共享的二進製文件。

R具有兩個函數 WriteBin()和 readBin()創建和讀取二進製文件。

語法

writeBin(object, con)
readBin(con, what, n )

以下是所使用的參數的說明:

  • con - 是連接對象讀或寫的二進製文件。
  • object - 是要被寫入的二進製文件。
  • 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中