I’ve been learning a lot these days. It’s been coming fast and heavy and I have not been able to document much of it. One of the areas I kind of focused on was Environments. I’ve glanced at (but not finished) the chapter Hadley Wickham wrote in his book ‘Advanced R’. One thing that stood out clearly was that environments are data structures just like any other in the language. I will pause there for now.
What I rushed out to post is something I just saw in a post in R Bloggers. The main gist was about loading .RData files safely and this is one area where environments can be put to good use.
Rather than loading the objects from that file into the Workspace (or global environment), just create a new environment with new.env()
and load the saved objects into into it by passing it as an argument to load()
. So, assuming we created an environment myEnv
, the call should look something like this
myEnv <- new.env() load("savedData.RData", envir = myEnv)
The reasons for this are explained in the blog post I just mentioned, but it boils down to reducing the risk of name conflicts between saved and already loaded objects.
And now I also know why it may be better to save objects as .RDS
files instead, since we can only save single objects, not a whole Workspace. But that is a topic for another day.
Reblogged this on The Opportunist.
LikeLike