A binary file is a file which contains information present only in the form of bits and bytes(0's and 1's). They are not human-readable because the bytes translate into characters and symbols that contain many other non-printable characters. If we will read a binary file using any text editor, it will show the characters like ð and Ø.
The code is relatively very easy to read binary data into R. To read binary data, we must know how a piece of information has been parsed into binary.
The binary file must be read by specific programs to be useful. For example, the binary file of a Microsoft Word program can only be read by the Word program in a human-readable form. It indicates that, in addition to human-readable text, there is a lot of information such as character formatting and page numbers, etc., which are also stored with alphanumeric characters. And finally, a binary file is a contiguous sequence of bytes. The line break we see in a text file is a character joining the first line to the next line.
Sometimes, the data generated by other programs need to be processed by R as a binary file. Also, R needs to create binary files that can be shared with other programs. There are two functions writeBin () and readBin () for creating and reading binary files in R.
Writing the Binary File
Like CSV and Excel files, we can also write into a binary file. R provides a writeBin() function for writing the data into a binary file. There is the following syntax of writeBin() function:
Here,
- The ?con' is the connection object which is used to write the binary file.
- The ?object' is the binary file in which we write our data.
Let's see an example to understand how this function is used to write data into a file in binary format. In the following example, we will use R inbuilt data "mtcars." We will create a CSV file from it and convert it into a binary file.
Example
Output
Reading the Binary File
We can also read our binary file which we have created before. For this purpose, R provides a readBin() function for reading the data from a binary file.
There is the following syntax of readbin() function:
Here,
- The ?con' is the connection object which is used to read the binary file.
- The ?what' is the mode such as character, integer, etc. which represent the bytes to be read.
- The ?n' is the number of bytes which we want to read from the binary file.
Let's see an example in which we read our binary data from binary.bin file.
Example
Output
No comments:
Post a Comment