R語言二進位檔

二進位檔是一個檔,其中包含僅以位和位元組形式存儲的資訊(01)。它們不可讀,因為其中的位元組轉換為包含許多其他不可列印字元的字元和符號。嘗試使用任何文本編輯器讀取二進位檔將顯示為類似Øð這樣的字元。

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

有時,由其他程式生成的數據需要由R作為二進位檔處理。 另外R需要創建可以與其他程式共用的二進位檔。

R有兩個函數用來創建和讀取二進位檔,它們分別是:WriteBin()readBin()函數。

語法

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

以下是使用的參數的描述 -

  • con - 是要讀取或寫入二進位檔的連接對象。
  • object - 是要寫入的二進位檔。
  • what - 是像字元,整數等的模式,代表要讀取的位元組。
  • n - 是從二進位檔讀取的位元組數。

實例

這裏考慮使用R內置數據“mtcars”。 首先,我們從它創建一個csv檔並將其轉換為二進位檔並將其存儲為操作系統檔。接下來將這個二進位檔讀入R中。

1. 寫入二進位檔

我們將數據幀“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)

2. 讀取二進位檔

上面創建的二進位檔將所有數據作為連續位元組存儲。 因此,我們將通過選擇列名稱和列值的適當值來讀取它。

# 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中的二進位檔,得到了原始數據。


上一篇: R語言Excel檔 下一篇: R語言基礎語法