2

I would like to save an arbitrary environment with saveRDS(). Whether global or custom, I was hoping saveRDS() would have the same behavior. However, the global environment seems like a special case.

ls()
## [1] "dl"  "gwd" "ld"  "td" # Helpers defined in my .Rprofile
x <- 1
ls()
## [1] "dl"  "gwd" "ld"  "td"  "x"
saveRDS(globalenv(), "global.rds")

Now, when I start a new R session and try to load the environment, x is dropped. This does not happen with a custom environment created with new.env(parent = globalenv()).

ls(readRDS("global.rds"))
## [1] "dl"  "gwd" "ld"  "td"

I expect this behavior is due to the fact that environments in R are really just collections of pointers. Still, I am looking for a way to save globalenv() with saveRDS(). I am currently using save.image() for my application, but it is a clunky special case that increases the demands on my testing workflow.

EDIT

If someone could elaborate on why exactly globalenv() does not really get saved, I would really appreciate it. I assume it is because of pointers, but that does not explain why this sort of thing does work for environments created with new.env(parent = globalenv()).

landau
  • 5,636
  • 1
  • 22
  • 50
  • `x <- 1; saveRDS(as.list(globalenv()), "bah.rds"); z <- readRDS("bah.rds"); names(z)` works fine for me. I'm not sure why you see it as better than save.image, though. – Frank Nov 07 '17 at 21:49
  • 1
    Unfortunately, I cannot convert the environment to/from a list in my case. My environment has functions, and because of lexical scoping, these functions need to stay connected to the original environment in which they were defined. – landau Nov 07 '17 at 21:53

0 Answers0