Search code examples
rpackageworkspace

In R can I save loaded packages with the workspace?


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?


Solution

  • 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