R writeBin() Function

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.


writeBin(object, con, size = NA, endian = .Platform$endian, useBytes = FALSE)


  1. object: It is an object containing the data to be written. It can be a raw vector or any R object coerced to raw.
  2. con: It is a connection object or a character string naming a file.
  3. size: The number of bytes to be written for each object element. If NA, the natural size of the object’s elements is used.
  4. endian: The endianness (byte order) to be used. Can be “big” or “little”. The default is the native format of your machine.
  5. 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


Output of writeBin() function

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)


[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.

Leave a Comment