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 specifiedfile.file: A string with the path to the.rdsfile.
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()withload(), which is used for.RDatafiles, 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
.RDatafiles 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.