0
0
R Programmingprogramming~5 mins

readRDS and saveRDS in R Programming

Choose your learning style9 modes available
Introduction

These functions help you save and load R objects easily. You can keep your work and use it later without redoing everything.

You want to save a data frame after cleaning it to use later.
You need to save a model you trained to use it again without retraining.
You want to share an R object with a friend or colleague.
You want to save your workspace objects before closing R.
Syntax
R Programming
saveRDS(object, file)
readRDS(file)

saveRDS() saves a single R object to a file.

readRDS() reads the saved object back into R.

Examples
Saves the object my_data to a file named data.rds.
R Programming
saveRDS(my_data, "data.rds")
Loads the saved object from data.rds into loaded_data.
R Programming
loaded_data <- readRDS("data.rds")
Saves a model object and then loads it back into new_model.
R Programming
saveRDS(model, "model.rds")
new_model <- readRDS("model.rds")
Sample Program

This program creates a list, saves it to a file, then loads it back and prints it.

R Programming
my_list <- list(name = "Alice", age = 30, scores = c(90, 85, 88))
saveRDS(my_list, "my_list.rds")
loaded_list <- readRDS("my_list.rds")
print(loaded_list)
OutputSuccess
Important Notes

The file saved by saveRDS() is binary and only readable by R.

You can save any R object, like vectors, lists, data frames, or models.

Use readRDS() to load the object and assign it to a variable.

Summary

saveRDS() saves one R object to a file.

readRDS() loads the saved object back into R.

These functions help keep your work safe and reusable.