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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With