您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)使用R語(yǔ)言怎么對(duì)二進(jìn)制文件進(jìn)行讀寫(xiě),文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
二進(jìn)制文件是一個(gè)文件,其中包含僅以位和字節(jié)形式存儲(chǔ)的信息(0和1),它們是不可讀的,因?yàn)槠渲械淖止?jié)轉(zhuǎn)換為包含許多其他不可打印字符的字符和符號(hào),隨便我們嘗試使用任何文本編輯器讀取二進(jìn)制文件將顯示為類似Ø和ð這樣的字符。
writeBin(object, con) readBin(con, what, n )
參數(shù)描述如下:
con - 是要讀取或?qū)懭攵M(jìn)制文件的連接對(duì)象。
object - 是要寫(xiě)入的二進(jìn)制文件。
what - 是像字符,整數(shù)等的模式,代表要讀取的字節(jié)。
n - 是從二進(jìn)制文件讀取的字節(jié)數(shù)。
我們接下來(lái)使用R內(nèi)置數(shù)據(jù)“mtcars”創(chuàng)建一個(gè)csv文件并將其轉(zhuǎn)換為二進(jìn)制文件并將其存儲(chǔ)為操作系統(tǒng)文件,如下:
#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)
運(yùn)行上面的文件就會(huì)產(chǎn)生一個(gè)csv文件和一個(gè)dat二進(jìn)制文件。這個(gè)dat文件將所有數(shù)據(jù)作為連續(xù)字節(jié)存儲(chǔ), 因此,我們將通過(guò)選擇列名稱和列值的適當(dāng)值來(lái)讀取它,如下:
#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)
關(guān)于使用R語(yǔ)言怎么對(duì)二進(jìn)制文件進(jìn)行讀寫(xiě)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。