How to save a standalone environment object R

I have been spending hours trying to do this job, and I 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 the entire workspace, the functions are saved and then loaded back (after closing / opening R Studio). But here save() and / or load() do not work, and after loading I only have a line in my environment.

How can I save a separate environment object to a file, and not a full workspace? Then I need all the objects inside this environment ( my_env ) to load into .GlobalEnv in another session.

+5
source share
1 answer

1) save / load . Your code works in that my_env being restored; however, load returns the names of the restored objects, not the objects themselves. The objects themselves are quietly restored as a side effect, and not through 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 use saveRDS and readRDS to save and restore individual objects. In this case, readRDS returns the object itself, not 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 in the search path, and not in the global environment:

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

Note. If you want to download the contents of my_env to the global environment, rather than loading my_env , you will have to copy the contents:

 for(el in ls(my_env)) assign(el, get(el, my_env)) 
+4
source

Source: https://habr.com/ru/post/1242566/


All Articles