R Advanced

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.

Syntax

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

Parameters

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

Recent Posts

Unlocking Statistical Consistency with set.seed in R

Picture this: You are playing Snakes and Ladder and need the dice to roll the…

1 month ago

What is copy-on-modify Semantics in R

The copy-on-modify semantics is a memory management technique that modifies one or more objects, copies…

2 months ago

How to Find Standard deviation in R [Using Real-life DataSet]

The standard deviation is a measure that tells you how spread out data are in…

8 months ago

How to Calculate Mean in R

Mean means the arithmetic average of a number in mathematics. An average is the sum…

8 months ago

How to Append an Element to a List at Any Position in R

List in R is a data structure that can hold multiple types of elements. You…

8 months ago

R ln() Function (SciViews Package)

The ln() function from the SciViews package calculates the natural log of the input vector.…

11 months ago