Let's look at ?save.image
:
save.image() is just a short-cut for ‘save my current workspace’, i.e., save(list = ls(all.names = TRUE), file = ".RData", envir = .GlobalEnv)
.
So, since you want finer control, you'll want to use save()
.
save(..., list = character(), file = stop("'file' must be specified"), ascii = FALSE, version = NULL, envir = parent.frame(), compress = isTRUE(!ascii), compression_level, eval.promises = TRUE, precheck = TRUE)
For save()
, you need to provide the list of objects to save, either in ...
or in list
. We can use ls()
to find all the objects in the environment.
So now, you get full control of the environment. By default, ls()
looks in the current environment, the one where it's called, which is the function execution environment (local):
x = 1
testfunction <- function(input){
a <- 2
output <- a + input
list_objects <- ls()
cat("In the current env, there are ",length(list_objects)," objects: ")
print(list_objects)
invisible(output)
}
testfunction(4)
#> In the current env, there are 3 objects: [1] "a" "input" "output"
Created on 2022-11-28 by the reprex package (v2.0.1)
So now we just want to save these objects with save(list = ls())
. But save()
by default looks in the parent.frame()
, i.e. the parent environment (here, the global environment), so we need to be explicit that we want to look in the current environment()
.
x = 1
testfunction <- function(input){
a <- 2
output <- a + input
list_objects <- ls()
save(list = list_objects, file = "test.rda", envir = environment())
invisible(output)
}
if(file.exists('test.rda')) file.remove('test.rda')
testfunction(4)
rm(list = ls())
ls()
#> character(0)
load('test.rda',
verbose = TRUE)
#> Loading objects:
#> a
#> input
#> output
ls()
#> [1] "a" "input" "output"
Created on 2022-11-28 by the reprex package (v2.0.1)
Note: for details on how environments work, see chapter 7 of Advanced R, particularly Section 7.4.4