Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a standalone R environment object

Tags:

r

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}
my_env[['echo']](123)
[1] 123
my_env$echo(123)
[1] 123
save(my_env, file = "MyEnv.RData", envir = .GlobalEnv)
loaded_env <- load(file = "MyEnv.RData",envir = .GlobalEnv)
typeof(loaded_env)
[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.

like image 402
V.B. Avatar asked Feb 08 '16 20:02

V.B.


1 Answers

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")
rm(my_env)
nms <- load("MyEnv.RData")
nms
## [1] "my_env"
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")
rm(my_env)
my_env <- readRDS("MyEnv.RData")
my_env
## <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")
rm(my_env)
attach("MyEnv.RData")
my_env
## <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))
like image 83
G. Grothendieck Avatar answered Oct 03 '22 07:10

G. Grothendieck