How to save and load environment objects in R

There was a need for me to build a prediction model in R and a Shiny app to allow users to get predictions out of my model. As the building of a prediction model take quite a while, it is not feasible for my shiny app to build the prediction model on demand.

There must be a way for my Shiny app to load my prediction model only once for fulfilling prediction requests from the users. As with many other programming languages, there are mechanisms in R that allow me to save my environment objects in one session and load them back in another session. This post documents how I can save and load environment objects in R.

Getting some objects into the environment

To demonstrate the ability of R in saving and loading objects, I first create some objects into the environment.

x = c(1,2,3)
y = c('Hello', 'World')
aList <- list()
aList['a'] <- 'a'
aList['b'] <- 'b'

Here I had created a Integer vector, a Character vector and a list of Character vectors. I then ran the following function to see if my objects had been saved to the current environment:

ls()

which gave me the following output:

[1] "aList" "x"     "y"

Saving the entire list of environment objects

After I had created some objects into the R environment, I used the save.image function to help me save the entire list of environment objects to a file. To do so, I ran the following function:

save.image(file='myEnvironment.RData')

This function ran the ls function to get the entire list of objects in the environment and save the objects as a file named 'myEnvironment.RData' in my current working directory.

To check if I had 'myEnvironment.RData', I ran the following function to get the files available in my current working directory:

dir()

and was able to see the newly created file that should contain the objects that I had created earlier:

[1] "myEnvironment.RData" 

Loading back the entire list environment of objects

To demonstrate that I can load back the objects that I had created, I first terminate my current R session by running the following function:

quit(save='no')

This function tells R to quit the current session without saving the environment data.

I then fire up a new R session and run the following function to load back the objects from 'myEnvironment.RData':

load('myEnvironment.RData')

This function looked up 'myEnvironment.RData' in my current working directory in order to load back the objects that are saved within the 'myEnvironment.RData' file.

I ran the ls function again to check whether my objects are loaded into the environment:

ls()

which produced the following output:

[1] "aList" "x"     "y"

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.