这篇文章将为大家详细讲解有关使用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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。