Making saveRDS() work for globalenv()

218 Views Asked by At

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()).

0

There are 0 best solutions below