Skip to content

R - Binary Files

R - Saving and Loading R Objects (Binary Files)

Section titled “R - Saving and Loading R Objects (Binary Files)”

In data analysis, you often need to save your work—data frames, models, or other R objects—so you can close your R session and resume later without rerunning your entire script. While you can use text files like CSV, saving to a binary file is often much more efficient and reliable for R-specific objects.

A binary file stores the object in a compressed, machine-readable format. This has two key advantages:

  1. Speed: Reading and writing are significantly faster than parsing text files.
  2. Fidelity: The exact R object is preserved, including data types, factor levels, and model attributes, which can be lost when converting to a flat text format.

The standard and most common way to save a single R object to a binary file is by using the saveRDS() and readRDS() functions. This is the recommended approach for saving intermediate results, processed data, or trained models.

# Save a single R object to a file
saveRDS(object, file = "path/to/your/file.rds")
# Read an R object from an RDS file
my_object <- readRDS(file = "path/to/your/file.rds")

Here’s a description of the parameters:

  • object: The R object you want to save (e.g., a data frame, a list, a model).
  • file: A string representing the path and filename. The .rds extension is a strong convention.

Let’s create a sample data frame, save it to an .rds file, remove it from our environment, and then load it back in.

# 1. Create a sample data frame
sample_data <- data.frame(
id = 1:5,
name = c("Alice", "Bob", "Charlie", "David", "Eve"),
score = c(8.5, 9.1, 7.3, 8.8, 9.9),
is_active = c(TRUE, FALSE, TRUE, TRUE, FALSE)
)
cat("--- Original Data Frame ---\n")
print(sample_data)
# 2. Save the data frame to an RDS file
saveRDS(sample_data, file = "sample_data.rds")
cat("\nObject 'sample_data' saved to 'sample_data.rds'\n")
# 3. Remove the object from the current R session
rm(sample_data)
# Verify that it's gone (this will cause an error)
# print(sample_data)
cat("\nObject 'sample_data' has been removed from the environment.\n")
# 4. Load the object back from the RDS file
loaded_data <- readRDS(file = "sample_data.rds")
cat("\n--- Loaded Data Frame ---\n")
print(loaded_data)

When you execute the above code, you will see the original data frame, confirmation messages, and then the perfectly restored data frame printed at the end.

--- Original Data Frame ---
id name score is_active
1 1 Alice 8.5 TRUE
2 2 Bob 9.1 FALSE
3 3 Charlie 7.3 TRUE
4 4 David 8.8 TRUE
5 5 Eve 9.9 FALSE
Object 'sample_data' saved to 'sample_data.rds'
Object 'sample_data' has been removed from the environment.
--- Loaded Data Frame ---
id name score is_active
1 1 Alice 8.5 TRUE
2 2 Bob 9.1 FALSE
3 3 Charlie 7.3 TRUE
4 4 David 8.8 TRUE
5 5 Eve 9.9 FALSE

Advanced: For Interoperability and Big Data

Section titled “Advanced: For Interoperability and Big Data”

While .rds files are perfect for R-to-R workflows, they are not readable by other programming languages like Python. For sharing data across different platforms, modern, high-performance binary formats are recommended:

  • Apache Feather (.feather or .arrow): Designed for extremely fast reading and writing of data frames between R and Python. The arrow package in R provides the interface.
  • Apache Parquet (.parquet): A columnar storage format optimized for big data. It’s highly compressed and efficient for reading only the columns you need. Also accessible via the arrow package.

Note: The original tutorial mentioned readBin() and writeBin(). These are low-level functions for reading and writing raw bytes from a connection. They are not suitable for saving and loading entire data frames or other complex R objects. Their use is rare and typically reserved for specialized applications like interacting with custom binary file formats or network protocols. For general data analysis, you should always prefer saveRDS() and readRDS().