Working with Binary Files in R Programming

04 Sep, 2021
In the computer science world, text files contain data that can easily be understood by humans. It includes letters, numbers, and other characters. On the other hand, binary files contain 1s and 0s that only computers can interpret. The information stored in a binary file can’t be read by humans as the bytes in it translate to characters and symbols that contain various other non-printable characters.It may happen some times when the data produced by other programs are essential to be processed by the R language as a binary file. Furthermore, R is necessarily responsible for creating binary files that can be shared with other programs. The four most important operations that can be performed in a binary file are:  
Creating and writing to a binary file
Reading from the binary file
Append to the binary file
Deleting the binary file
 
The both creating and writing to a binary file can be performed by a single function writeBin() by opening the file in “wb” mode where w indicates write and b indicates binary mode. 
Syntax: writeBin(object, con)Parameters: object: an R object to be written to the connection con: a connection object or a character string naming a file or a raw vector.  
Example:  
Python3
# R program to illustrate# working with binary file # Creating a data framedf = data.frame(  "ID" = c(1, 2, 3, 4),  "Name" = c("Tony", "Thor", "Loki", "Hulk"),  "Age" = c(20, 34, 24, 40),  "Pin" = c(756083, 756001, 751003, 110011)) # Creating a connection object# to write the binary file using mode "wb"con = file("myfile.dat", "wb") # Write the column names of the data frame# to the connection objectwriteBin(colnames(df), con) # Write the records in each of the columns to the filewriteBin(c(df$ID, df$Name, df$Age, df$Pin), con) # Close the connection objectclose(con)
Output:  
 
Reading from the binary file can be performed by a the function readBin() by opening the file in “rb” mode where r indicates read and b indicates binary mode. 
Syntax: readBin(con, what, n )Parameters: con: a connection object or a character string naming a file or a raw vector what: either an object whose mode will give the mode of the vector to be read or a character vector of length one describing the mode: one of “numeric”, “double”, “integer”, “int”, “logical”, “complex”, “character”, “raw” n: the (maximal) number of records to be read  
Example:  
Python3
# R program to illustrate# working with binary file # Creating a connection object# to read the file in binary mode using "rb".con = file("myfile.dat", "rb") # Read the column names# n = 4 as here 4 columncolname = readBin(con, character(),  n = 4) # Read column values# n = 20 as here 16 values and 4 column namescon = file("myfile.dat", "rb")bindata = readBin(con, integer(), n = 20) # Read the ID values# as first 1:4 byte for col name# then values of ID col is within 5 to 8ID = bindata[5:8] # Similarly 9 to 12 byte for values of name columnName = bindata[9:12] # 13 to 16 byte for values of the age columnAge = bindata[13:16] # 17 to 20 byte for values of Pincode columnPinCode = bindata[17:20] # Combining all the values and make it a data framefinaldata = cbind(ID, Name, Age, PinCode)colnames(finaldata)= colnameprint(finaldata)
Output:  
             ID       Name        Age        Pin
[1, ]          0          0          0          0
[2, ] 1072693248 1074266112 1074790400 1073741824
[3, ]          0          0          0          0
[4, ] 1073741824 1074790400 1074266112 1072693248
 
Append to the binary file can be performed by a the same function writeBin() by opening the file in “ab” mode where a indicates append and b indicates binary mode.Example:  
Python3
# R program to illustrate# working with binary file # Creating another data frame# to append with the existing data framedf = data.frame(  "Salary" = c(100, 200, 300, 400),  "Experience" = c(3, 5, 10, 4)) # Creating a connection object# to append the binary file using mode "ab"con = file("myfile.dat", "ab") # append the column names of the data frame# to the connection objectwriteBin(colnames(df), con) # append the records in each of the columns to the filewriteBin(df$Salary, con) # Close the connection objectclose(con)
Output:  
 
In R, one can delete the binary file by using file.remove() command and then unlink the deleted file by using unlink() function.Example:  
Python3
# R program to illustrate# working with binary file # Define the file name that will be deletedfileName <- "myfile.dat" # Check its existenceif (file.exists(fileName))  # Delete file if it exists  file.remove(fileName) # Unlink the deleted fileunlink(fileName, recursive = TRUE)
sagartomar9927
Picked
R-FileHandling
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change column name of a given DataFrame in R
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
How to Split Column Into Multiple Columns in R DataFrame?
Change Color of Bars in Barchart using ggplot2 in R
Adding elements in a vector in R programming - append() method
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Convert Factor to Numeric and Numeric to Factor in R Programming