Mike
Mike

Reputation: 1141

Saving R objects conditional on whether they exist

At the end of an analysis I'd like to save some of the R environment objects. However, I reuse this script and sometimes some of the objects don't exist. I don't want to have to edit the save statement each time, so I'd like the script to accommodate when an object doesn't exist. I'm struggling to get this to work with exist though.

save(if(exists("object1")) {object},
       if(exists("object2")) {object2},
       file = "./my_saved_environment/saved_objects.RData")

Upvotes: 1

Views: 295

Answers (1)

r2evans
r2evans

Reputation: 160447

Use save(file=...) and a character vector, intersecting with the variables you want. For example:

ls()
# [1] "airquality" "aqm"        "dat"        "mydata"    
intersect(ls(), c("mydata", "quux"))
# [1] "mydata"                                # quux does not exist

save(list = intersect(ls(), c("mydata", "quux")), file = "quux.rda")

And if we look at the .rda file, this is what is saved:

e <- new.env(parent = emptyenv())
load("quux.rda", envir = e)
ls(envir = e)
# [1] "mydata"

You can also form the list of objects to save programmatically, perhaps using grep("^mydata.*", ls(), value=TRUE) or similar.

Upvotes: 4

Related Questions