SoFunction
Updated on 2025-04-21

R language.rdata file saving and loading operation method

In R, the .rdata file is created with the save() function.

  • Use the save() function to save one or more R objects into a .rdata file.
  • Use the load() function to restore objects in the .rdata file to the current work environment.

1. Create and save the object to .rdata

Suppose there is a linear regression model trained on the iris dataset and want to save it to a .rdata file:

# Load the necessary packageslibrary(tidymodels)
# Train a simple model using the iris dataset(123) # Set random seeds to ensure results are repeatablemodel <- linear_reg() %>%
  set_engine("lm") %>%
  fit( ~ , data = iris)
# View model summarysummary(model)
# Save the model as a .rdata filesave(model, file = "models/tidymodels_iris.rdata")
  • A linear regression model was trained using the linear_reg() function in the tidymodels package.
  • Use the save() function to save the model object (model) to the models/tidymodels_iris.rdata file.

2. Save multiple objects to the same .rdata file

# Create some extra objectspredictions <- model %>% predict(new_data = iris)
metrics <- metrics(truth = iris$, estimate = predictions$.pred)
# Save the model, predicted values ​​and evaluation metrics togethersave(model, predictions, metrics, file = "models/tidymodels_iris.rdata")

The models/tidymodels_iris.rdata file will contain three objects: model, predictions, and metrics.

3. Load and check saved content

# Load the .rdata fileload("models/tidymodels_iris.rdata")
# View objects in the work environmentls()
# Check the specific content of an objectsummary(model)
head(predictions)
print(metrics)

4. Things to note

  • Path issue: Make sure the paths are correct when saving and loading the file. If the path is incorrect, R may not be able to find the file.
  • Object Naming: The object name saved to the .rdata file will be preserved. Therefore, after loading the file, these objects can be accessed directly by the name.
  • Version Compatibility: The .rdata file is in binary format and may depend on the version and operating system of R. Try to save and load files in the same environment.

This is the article about the operation method of saving and loading of R language.rdata files. For more information about saving content of R language.rdata files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!