
- R 教程
- R - 首頁
- R - 概述
- R - 環境設定
- R - 基本語法
- R - 資料型別
- R - 變數
- R - 運算子
- R - 決策
- R - 迴圈
- R - 函式
- R - 字串
- R - 向量
- R - 列表
- R - 矩陣
- R - 陣列
- R - 因子
- R - 資料框
- R - 包
- R - 資料重塑
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 檔案,並將其轉換為二進位制檔案,並將其儲存為作業系統檔案。接下來,我們將建立的此二進位制檔案讀入 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 中讀取二進位制檔案獲得了原始資料。
廣告