R語言實現二進制文件讀寫操作

二進制文件是一個文件,其中包含僅以位和字節形式存儲的信息(0和1),它們是不可讀的,因為其中的字節轉換為包含許多其他不可打印字符的字符和符號,隨便我們嘗試使用任何文本編輯器讀取二進制文件將顯示為類似Ø和ð這樣的字符。

但是二進制文件必須由特定程序讀取才能使用。例如,Microsoft Word程序的二進制文件隻能通過Word程序讀取到人類可讀的形式。這表明,除瞭人類可讀的文本之外,還有更多的信息,如格式化的字符和頁碼等,它們也與字母數字字符一起存儲。最後,二進制文件是一個連續的字節序列。 我們在文本文件中看到的換行符是將第一行連接到下一個的字符。

有時,由其他程序生成的數據需要由R作為二進制文件處理,另外R需要創建可以與其他程序共享的二進制文件,在R中有兩個函數用來創建和讀取二進制文件,它們分別是:WriteBin()和readBin()函數,來看下語法:

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

參數描述如下:

  • con – 是要讀取或寫入二進制文件的連接對象。
  • object – 是要寫入的二進制文件。
  • what – 是像字符,整數等的模式,代表要讀取的字節。
  • n – 是從二進制文件讀取的字節數。

我們接下來使用R內置數據“mtcars”創建一個csv文件並將其轉換為二進制文件並將其存儲為操作系統文件,如下:

#my first R program
 
# 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("D:/r_file/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)

運行上面的文件就會產生一個csv文件和一個dat二進制文件。這個dat文件將所有數據作為連續字節存儲, 因此,我們將通過選擇列名稱和列值的適當值來讀取它,如下:

#my first R program
 
# Create a connection object to read the file in binary mode using "rb".
read.filename <- file("D:/r_file/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("D:/r_file/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)

上述代碼演示瞭幾種輸出的方式,大傢有興趣的可以自己擴展下。

到此這篇關於R語言實現二進制文件讀寫操作的文章就介紹到這瞭,更多相關R語言 二進制文件讀寫操作內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: