A binary file in a computer system is a file that contains information stored only in the form of bits and bytes. (0’s and 1’s). Binary characters are not human-readable and it is only understood by machines. The binary file has to be read by special programs to be useable.
readBin in R
To read binary data in R, use the readBin() function. To write binary data in R, use the writeBin() function.
readBin(con, what, n = 1L, size = NA_integer_, signed = TRUE, endian = .Platform$endian)
con: It is a connection object or a character string naming a file or a raw vector.
what: It is 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: It is numeric. The (maximal) number of records to be read. You can use an over-estimate here, but not too large as storage is reserved for n items.
size: It is the integer. The number of bytes per element in the byte stream. The default, NA_integer_, uses the natural size. Size changing is not supported for raw and complex vectors.
signed: It is logical. Only used for integers of sizes 1 and 2 when it determines if the quantity on file should be regarded as a signed or unsigned integer.
endian: It is an endian-ness (“big” or “little”) of the target system for the file. Using “swap” will force swapping endian-ness.
The readBin() function returns a vector of appropriate mode and length the number of items reads.
Let’s create a binary file using the writeBin() function and then read that file using the readBin() function.
tf <- tempfile() x <- as.integer(c(-1, 2) * 3 ^ (0:19)) writeBin(con = tf, x) readBin(tf, integer(), n = 20) unlink(tf)
Warning message: NAs introduced by coercion to integer range  -1 6 -9 54 -81 486  -729 4374 -6561 39366 -59049 354294  -531441 3188646 -4782969 28697814 -43046721 258280326  -387420489 NA
To remove the file in R, use the unlink() function.
The binary file is created stores all the data as contiguous bytes, and then we are reading it one by one.
That is it for readBin() function in R.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.