6

R normally only saves objects in .GlobalEnv:

$ R
> library(rjson)
> fromJSON
function (...) ...
> q(save='yes')
$ R
> fromJSON
Error: object 'fromJSON' not found

Is there a way to have this information saved as well?

Owen
  • 38,836
  • 14
  • 95
  • 125

4 Answers4

5

You are now able to save R session information to a file and load it in another session.

First install the "session" package:

install.packages('session')

Load your libraries and your data, then save the session state to a file:

library(session)
library(ggplot2) # plotting

test <- 100

save.session(file='test.Rda')

Then you can load the session state in another session:

library(session)

restore.session(file='test.Rda')

#ggplot2 (and associated data) should have loaded with the session data
head(diamonds)
ggplot(data = diamonds, aes(x = carat)) +
  geom_histogram()

print(test)

Reference: https://www.rdocumentation.org/packages/session/versions/1.0.3/topics/save.session

ConnectedSystems
  • 892
  • 10
  • 19
5

To the best of my knowledge, no. The workspace is for objects like data and functions. Starting R with particular packages loaded is what your .Rprofile file is for, and you can have a different one in each directory.

You could, I suppose, save a function in the workspace that loads the packages you want, and then run that function when you first start R.

joran
  • 169,992
  • 32
  • 429
  • 468
2

joran is right, but I want to mention a technique that, while cumbersome, might be helpful.

You can use a checkpointing program such as DMTCP to save the entire R process and restart it later.

Owen
  • 38,836
  • 14
  • 95
  • 125
2

I'd recommend not saving anything between r sessions and instead recreate it all using code. This is much more likely to lead to reproducible results.

hadley
  • 102,019
  • 32
  • 183
  • 245
  • 2
    True, and I always try and get everything into code that can be straight-up run when I'm finished, it's just that it gets slow repeatedly running longer and longer scripts. – Owen Aug 19 '11 at 20:59
  • 1
    Beware also the order in which you include packages, as objects from one may shadow another. – smci Feb 09 '14 at 10:25