Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 561
Owen Avatar asked Aug 18 '11 23:08

Owen


2 Answers

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

like image 138
ConnectedSystems Avatar answered Sep 28 '22 14:09

ConnectedSystems


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.

like image 44
joran Avatar answered Sep 28 '22 13:09

joran