Open In App

saveRDS() and readRDS() Functions in R

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The saveRDS function is a serialization interface for single objects and it is usually used with the readRDS function. Both saveRDS and readRDS are used for saving individual R Programming Language objects to a connection usually called a file and to restore these objects under different names.

saveRDS() and readRDS() Functions in R

All the interfaces like saveRDS and readRDS, save & load, serialize & unserialize use the same serialization format – “.rds”. saveRDS and readRDS are not similar to save and load functions, they save and load one or more named objects in an environment. They are usually used by R for storing the metadata of a package or to store the help. search databases.

Functions like serialize and unserialize also provide a slightly lower-level interface to serialization. Objects serialized to a connection (a file) by serialize can be read back by readRDS and vice versa.

Syntax:

saveRDS(object, file = "", ascii = FALSE, version = NULL, compress = TRUE, refhook = NULL)

readRDS(file, refhook = NULL)
  • object: R object intended for serialization
  • file: A connection or the filename where the R object will be stored.
  • ascii: When set to TRUE, an ASCII representation of the data is generated. By default, ascii is FALSE, resulting in the creation of a binary file. If set to NA and version >= 2, an alternative ASCII representation is used, specifically encoding double/complex numbers as binary fractions.
  • version: Setting to NULL uses the current default version (3). Alternatively, version 2 can be specified, which was the default from R 1.4.0 to R 3.5.0.
  • compress: A logical value indicating whether compression should be applied when saving to a named file. Options include “gzip”, “bzip2”, or “xz” to specify the compression type. This parameter is ignored if file is a connection.
  • refhook: A hook function designed for managing reference objects.

Compression is managed by the connection established when file is a filename. Therefore, compression is only possible if the connection handles it. For example, URL connections may necessitate wrapping in a call to gzcon.

If a connection is provided, it will be opened (in binary mode) throughout the function’s execution, provided it isn’t already open. Also, if the connection is already open, it must be in binary mode for saveRDS(ascii = FALSE) or to read non-ASCII saves.

Files produced by saveRDS are not suitable as an interchange format between machines, for example to download from a website.

Saving and Loading Data Frames in R Using saveRDS() and readRDS()

This example shows how to save a data frame to a file using the saveRDS() function, and then load it back into R using the readRDS() function. The data frame “my_data” containing names and ages is saved to a file named “data.rds” and then removed from the workspace. Later, the data is loaded back from the file and stored in the variable “loaded_data”, which is then displayed.

R
# Sample data frame
my_data <- data.frame(
  Name = c("Shravan", "Jeetu", "Lakhan", "Pankaj"),
  Age = c(20, 18, 18, 19)
)

# Display the data frame
cat("Original Data:\n")
print(my_data)

# Save the data frame to a file named "data.rds"
# The file will be saved in the current working directory
# Specify the path if you want to save it in a different location
saveRDS(my_data, "data.rds")

# Remove the data frame from the workspace
rm(my_data)

# Load the data frame back from the file
loaded_data <- readRDS("data.rds")

# Display the loaded data frame
cat("\nLoaded Data:\n")
print(loaded_data)

Output:

Original Data:
Name Age
1 Shravan 20
2 Jeetu 18
3 Lakhan 18
4 Pankaj 19

Loaded Data:
Name Age
1 Shravan 20
2 Jeetu 18
3 Lakhan 18
4 Pankaj 19

We can see this saved file in R Studio enviourment.

Screenshot-2024-04-08-111250

saveRDS() and readRDS() Functions in R

Saving and Loading Lists with Various Data Types in R Using saveRDS() and readRDS()

This code snippet shows how to save a list containing different data types, including numeric vectors, character vectors, logical values, and matrices, to a file using saveRDS(). After saving, the original list is removed from the environment. Later, the list is loaded back from the file using readRDS() and stored in the variable “loaded_list”. The structure of the loaded list is then checked using str() to confirm successful loading.

R
# Create a list with different data types
my_list <- list(num_vec = 1:5,
                char_vec = c("Shravan", "Jeetu", "Ram"),
                logical_val = TRUE,
                matrix_data = matrix(1:9, nrow = 3))

# Save the list to a file
saveRDS(my_list, file = "my_list.rds")
# Remove the list from the environment
rm(my_list)

# Load the list back from the file
loaded_list <- readRDS("my_list.rds")

# Check the loaded list
str(loaded_list)

Output:

List of 4
$ num_vec : int [1:5] 1 2 3 4 5
$ char_vec : chr [1:3] "Shravan" "Jeetu" "Ram"
$ logical_val: logi TRUE
$ matrix_data: int [1:3, 1:3] 1 2 3 4 5 6 7 8 9

Saving and Loading Custom Functions in R Using saveRDS() and readRDS()

This example shows the process of saving a custom function, in this case, a square root function, to a file using saveRDS(). After saving, the original function is removed from the environment. Later, the function is loaded back from the file using readRDS() and stored in the variable “loaded_func”. Finally, the loaded function is used to calculate the square root of a number (in this case, 16) showing the successful loading of the function.

R
# Define a custom function
square_root <- function(x) sqrt(x)

# Save the function to a file
saveRDS(square_root, file = "sqrt_func.rds")

# Remove the function from the environment
rm(square_root)

# Load the function back from the file
loaded_func <- readRDS("sqrt_func.rds")

# Use the loaded function
loaded_func(16)

Output:

[1] 4

Using Temporary Files to Save and Load Data Frames in R with saveRDS() and readRDS()

This example shows how to use temporary files to save and load a data frame in R using saveRDS() and readRDS(). The built-in iris dataset is used as an example. First, the data frame is saved to a temporary file created by tempfile(). After saving, the original data frame is removed from the environment. Then, the data frame is loaded back from the temporary file using readRDS(). The loaded data frame is checked using head() to ensure successful loading. Finally, the temporary file is cleaned up using unlink(). This approach ensures better handling of data frames without overloading the workspace with unnecessary files.

R
# Create a data frame
iris_data <- iris

# Create a temporary file
temp_file <- tempfile(fileext = ".rds")

# Save the data frame to the temporary file
saveRDS(iris_data, file = temp_file)

# Remove the data frame from the environment
rm(iris_data)

# Load the data frame back from the temporary file
loaded_data <- readRDS(file = temp_file)

# Check the loaded data
head(loaded_data)

# Clean up the temporary file
unlink(temp_file)

Output:

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

Compressing Data Frames in R Using saveRDS()

This example shows how to compress data frames when saving them in R using the saveRDS() function. First, a large data frame “large_df” is created. Then, it is saved twice: once without compression (“large_df_uncompressed.rds”) by setting the compress parameter to FALSE, and once with compression (“large_df_compressed.rds”) by setting the compress parameter to TRUE. This shows how to apply compression to reduce file sizes when saving data frames using saveRDS().

R
# Create a large data frame
large_df <- data.frame(x = rnorm(1e6), y = rnorm(1e6))

# Save without compression
saveRDS(large_df, file = "large_df_uncompressed.rds", compress = FALSE)

# Save with compression
saveRDS(large_df, file = "large_df_compressed.rds", compress = TRUE)

# Check the file sizes
file.info("large_df_uncompressed.rds")$size
file.info("large_df_compressed.rds")$size

Output:

[1] 16000186
[1] 15356551


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads