您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關使用R語言怎么對二進制文件進行讀寫,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
二進制文件是一個文件,其中包含僅以位和字節形式存儲的信息(0和1),它們是不可讀的,因為其中的字節轉換為包含許多其他不可打印字符的字符和符號,隨便我們嘗試使用任何文本編輯器讀取二進制文件將顯示為類似Ø和ð這樣的字符。
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語言怎么對二進制文件進行讀寫就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。