Skip to content

Use saveRDS/readRDS instead of save/load #3735

@ashiklom

Description

@ashiklom

Description

save saves objects according to their name in the current environment, and load reads them into the target environment under the name that they were saved. This creates some problems/annoyances:

For save, the following will throw a (confusing) error because the object literally called 'mylist[["thing1"]]' does not exist in the environment.

mylist <- list(thing1 = "something", thing2 = "something_else")
save(mylist[["thing1"]], file = "thing1.RData")
# Error in save(mylist[["thing1"]], file = "thing1.RData") : 
#   object ‘mylist[["thing1"]]’ not found

To accomplish this, you need to do annoying things like:

thing1 <- mylist[["thing1"]]
save(thing1, file = "thing1.RData")
rm(thing1)

For load, to read specific objects into other names, we need to do some awkward gymnastics with environments, like:

myenv <- new.env()
load("thing1.RData", envir = myenv)
thing1a <- myenv$thing1

If you don't do that, load will silently override objects with the same name in the current environment:

thing1 <- "something else"
load("thing1.RData")
print(thing1)
# [1] "something"   # NOTE: `thing1` has been overridden!

Proposed Solution

All of these problems go away with saveRDS / readRDS.

saveRDS(mylist[["thing1"]], file = "thing1.rds")
thing1a <- readRDS("thing1.rds")

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions