Home Ask Login Register

Developers Planet

Your answer is one click away!

V.B. February 2016

How to save a standalone R environment object

I am spending already hours trying to make this work and feel that I am missing something simple:

my_env = new.env(hash = TRUE, parent = .GlobalEnv)
my_env[['echo']] <- function(x) {x}
[1] 123
[1] 123
save(my_env, file = "MyEnv.RData", envir = .GlobalEnv)
loaded_env <- load(file = "MyEnv.RData",envir = .GlobalEnv)
[1] "character"

When I save entire workspace, functions are saved and then loaded back (after I close/open R Studio). But here, save() and/or load() do not work, and I have only a string in my environment after loading.

How could I save a separate environment object to a file, not a complete workspace? I then need all objects inside that environment (my_env) to be loaded into .GlobalEnv in another session.


G. Grothendieck February 2016

1) save/load Your code does work in that my_env is restored; however, load returns the names of the restored objects, not the objects themselves. The objects themselves are silently restored as a side effect rather than via the return value.

save(my_env, file = "MyEnv.RData")
nms <- load("MyEnv.RData")
## [1] "my_env"
## [1] <environment: 0x000000000bfa5c70>

2) saveRDS/readRDS You can alternately use saveRDS and readRDS to save and restore single objects. In that case readRDS return the object itself rather than its name unlike load.

saveRDS(my_env, file = "MyEnv.RData")
my_env <- readRDS("MyEnv.RData")
## <environment: 0x000000000bfb45f8>

3) save/attach Another possibility is to place MyEnv.RData on the search path rather than in the global environment:

save(my_env, file = "MyEnv.RData")
## <environment: 0x000000000b072188>

Note: If you wish to load the contents of my_env into the global environment rather than loading my_env itself you will have to copy the contents out:

for(el in ls(my_env)) assign(el, get(el, my_env))

Post Status

Asked in February 2016
Viewed 2,025 times
Voted 12
Answered 1 times


Leave an answer

Quote of the day: live life