I like the idea of working with workspaces. So far I always saved entire workspaces and loaded them entirely to an existing project. But a lot of times I only need single objects from a specified workspace. Is there a possibility to load them seperatly from another workspace.
Also sometimes it would be nice to add an object to an already existing workspace. Imagine for example you have five huge scripts with seperatly huge workspaces and you don't want to mix them up to have them all in one workspace. So now you want to store only the clean results from each of the five worspaces to another clean workspace...
So theses are the basic tasks:
# save entire workspace
save.image("mypath/myworkspace")
# load entire workspace
load ("mypath/myworkspace")
# save a single object (or several)
save (myobject,file="mypath/myworkspace")
# load a single object from an existing workspace
?
# add a single object to an existing workspace
?
RStudio calls your globalenv()
your "workspace"
You can load .RData files into environments other than your globalenv()
x <- 1; y <- 2 #First, create some objects
save.image() # save workspace to disk
rm(list=ls()) # remove everything from workspace
tmp.env <- new.env() # create a temporary environment
load(".RData", envir=tmp.env) # load workspace into temporary environment
x <- get("x", pos=tmp.env) # get the objects you need into your globalenv()
#x <- tmp.env$x # equivalent to previous line
rm(tmp.env) # remove the temporary environment to free up memory
Once an object is in your globalenv()
, it will show up in RStudio's "Workspace" tab.
Similarly, you can assign objects into the environment.
tmp.env <- new.env()
load(".RData", envir=tmp.env) # load workspace into temporary environment
assign("z", 10, pos=tmp.env)
#tmp.env$z <- 10 # equivalent to previous line
Now, you can save all the objects in tmp.env
if you tell save
where they are located.
save(list=ls(all.names=TRUE, pos=tmp.env), envir=tmp.env, file="test.RData")
rm(tmp.env)
You have effectively added an object, z
, to the workspace stored in test.RData.
rm(list=ls(all.names=TRUE))
load("test.RData")
> ls()
[1] "x" "y" "z"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With