RDS Files
in R Programming
Learn how to serialize and deserialize R objects using saveRDS() and readRDS() for efficient data storage and sharing.
What Is Serialization?
Serialization is the process of converting an R object in memory into a stream of bytes that can be saved to a file. Deserialization is the reverse: reading those bytes back and reconstructing the original object.
What Is an RDS File?
An RDS file (R Data Serialization) stores a single R object in a compressed binary format. It preserves the object's type, class, attributes, and all internal structure.
Why Use RDS Files?
The Core Functions: saveRDS and readRDS
saveRDS() In Detail
readRDS() In Detail
.rds vs .RData: Key Distinction
| .rds (saveRDS/readRDS) | .RData (save/load) | |
|---|---|---|
| Objects per file | Exactly one | One or more |
| Name binding | No: you assign on read | Yes: original names restored |
| Write function | saveRDS(obj, file) | save(obj1, obj2, file) |
| Read function | x <- readRDS(file) | load(file) |
| Overwrite risk | Low | High |
.rds vs .csv: When to Choose
| .rds | .csv | |
|---|---|---|
| Format | Binary (compressed) | Plain text |
| Preserves types | ✓ factors, dates, lists | ✕ everything becomes text |
| Speed | Fast | Slower (parsing) |
| Cross-platform | R only | Any language |
| Human-readable | ✕ | ✓ |
How to Apply RDS in Your Workflow
Example 1: Saving a Data Frame
Example 2: Saving a Fitted Model
Example 3: Saving a Complex List
Compression Options
Common Mistakes
Summary: RDS Cheat Sheet
| Task | Code |
|---|---|
| Save one object | saveRDS(obj, "file.rds") |
| Read one object | x <- readRDS("file.rds") |
| Use xz compression | saveRDS(obj, "f.rds", compress = "xz") |
| No compression | saveRDS(obj, "f.rds", compress = FALSE) |
| Check restored type | class(readRDS("file.rds")) |
Question 1 of 5
Which function do you use to save a single R object to an RDS file?
Question 2 of 5
What happens if you run readRDS("data.rds") without assigning the result to a variable?
Question 3 of 5
Which data type would you lose if you saved a data frame to CSV instead of RDS?
Question 4 of 5
A key advantage of .rds over .RData is that:
Question 5 of 5
Which compression option produces the smallest file size when using saveRDS()?