The writeBin() function in R is used to write binary data to a file. It is a low-level function for writing binary data and requires understanding binary formats and data representation.
It saves geographic data as a byte file in gzip compressed format (‘.gz’). Unfortunately, it only works with 2D (one-layer) spatial objects.
Syntax
writeBin(object, con, size = NA, endian = .Platform$endian, useBytes = FALSE)
Parameters
- object: It is an object containing the data to be written. It can be a raw vector or any R object coerced to raw.
- con: It is a connection object or a character string naming a file.
- size: The number of bytes to be written for each object element. If NA, the natural size of the object’s elements is used.
- endian: The endianness (byte order) to be used. Can be “big” or “little”. The default is the native format of your machine.
- useBytes: Logical. If TRUE, an object is written as bytes.
Return Value
It returns NULL or a raw vector (if con is a raw vector). Ensure the connection is opened in the appropriate mode (“wb” for writing binary data).
Example 1: Writing binary data to a file
# Example raw data
raw_data <- charToRaw("Hello World")
# Create a connection to a binary file
file_conn <- file("example.bin", "wb")
# Write raw data to the file
writeBin(raw_data, file_conn)
# Close the connection
close(file_conn)
Output
Example 2: Usage with readBin() and unlink()
tf <- tempfile()
x <- as.integer(c(-2, 1) * 2 ^ (0:21))
writeBin(con = tf, x)
readBin(tf, integer(), n = 20)
unlink(tf)
Output
[1] -2 2 -8 8 -32 32 -128 128 -512
[10] 512 -2048 2048 -8192 8192 -32768 32768 -131072 131072
[19] -524288 524288
That is it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.