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:
- Speed: Reading and writing are significantly faster than parsing text files.
- 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 Modern Approach: RDS Files
Section titled “The Modern Approach: RDS Files”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.
Syntax
Section titled “Syntax”# Save a single R object to a filesaveRDS(object, file = "path/to/your/file.rds")
# Read an R object from an RDS filemy_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
.rdsextension is a strong convention.
Example: Saving and Loading a Data Frame
Section titled “Example: Saving and Loading a Data Frame”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 framesample_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 filesaveRDS(sample_data, file = "sample_data.rds")cat("\nObject 'sample_data' saved to 'sample_data.rds'\n")
# 3. Remove the object from the current R sessionrm(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 fileloaded_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_active1 1 Alice 8.5 TRUE2 2 Bob 9.1 FALSE3 3 Charlie 7.3 TRUE4 4 David 8.8 TRUE5 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_active1 1 Alice 8.5 TRUE2 2 Bob 9.1 FALSE3 3 Charlie 7.3 TRUE4 4 David 8.8 TRUE5 5 Eve 9.9 FALSEAdvanced: 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 (
.featheror.arrow): Designed for extremely fast reading and writing of data frames between R and Python. Thearrowpackage 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 thearrowpackage.
Deprecated Method: readBin and writeBin
Section titled “Deprecated Method: readBin and writeBin”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().