0
0
R-programmingHow-ToBeginner ยท 3 min read

How to Read RDS File in R: Simple Guide

To read an .rds file in R, use the readRDS() function with the file path as its argument. This function loads the saved R object back into your R session.
๐Ÿ“

Syntax

The basic syntax to read an RDS file is:

  • readRDS(file): Reads the R object stored in the specified file.
  • file: A string with the path to the .rds file.

The function returns the R object saved in the file, which you can assign to a variable.

r
object <- readRDS("path/to/file.rds")
๐Ÿ’ป

Example

This example shows how to save a simple data frame to an RDS file and then read it back into R.

r
df <- data.frame(Name = c("Alice", "Bob"), Age = c(25, 30))
saveRDS(df, "example.rds")
read_df <- readRDS("example.rds")
print(read_df)
Output
Name Age 1 Alice 25 2 Bob 30
โš ๏ธ

Common Pitfalls

Common mistakes when reading RDS files include:

  • Using readRDS() without assigning the result to a variable, which means the object is read but not saved for use.
  • Providing an incorrect file path or filename, causing an error.
  • Confusing readRDS() with load(), which is used for .RData files, not .rds.
r
## Wrong: Not assigning the read object
readRDS("example.rds")

## Right: Assign to variable
my_data <- readRDS("example.rds")
๐Ÿ“Š

Quick Reference

Remember these tips when working with RDS files:

  • Use saveRDS(object, file) to save a single R object.
  • Use readRDS(file) to read it back.
  • Always assign the result of readRDS() to a variable.
  • RDS files store one R object, unlike .RData files which can store multiple.
โœ…

Key Takeaways

Use readRDS() with the file path to load an RDS file in R.
Assign the output of readRDS() to a variable to use the loaded object.
Ensure the file path is correct to avoid errors.
RDS files store a single R object, unlike .RData files.
Do not confuse readRDS() with load(), which is for .RData files.