```r

Save all the objects in both a function and the global environment and load them all back into the global env.

test <- function() {

# These objects, which are locally to this function, are normally lost when the function exits. aa <- 789 bb <- "Hello"

save(list = c(ls(), names(.GlobalEnv)), file = "Image & Function objects.RData") # Save all objects inside this function and the global env. }

cc <- "GlobalEnv File"

test() ls()

rm(list = ls()) # Remove all objects

load("Image & Function objects.RData") # Load both the global objects and all objects inside the function back into the global env.

rm(list = ls()) # Cleanup

----------------------------------------------------------------------------------------------------------------------------------------

Save all the objects in a function and load them back into the global env.

test2 <- function() {

# These objects, which are locally to this function, are normally lost when the function exits. aa <- 790 bb <- "Hello again"

save(list = ls(), file = "All function objects.RData") # Save all objects inside this function. }

cc <- "GlobalEnv File"

test2() ls()

rm(list = ls()) # Remove all objects

load("All function objects.RData") # Load all objects inside the function back into the global env, but not the global objects.

rm(list = ls()) # Cleanup

----------------------------------------------------------------------------------------------------------------------------------------

Save all the objects in a function and load them back into the global environment on function exit.

test3 <- function() {

# These objects, which are locally to this function, are normally lost when the function exits. aa <- 791 bb <- "Hello for a second time"

save(list = ls(), file = "All function objects.RData") # Save all objects inside this function. on.exit(load("All function objects.RData")) on.exit(file.remove("All function objects.RData"), add = TRUE) # Optionally remove the file on exit }

cc <- "GlobalEnv File"

test3() ls()

rm(list = ls()) # Cleanup

----------------------------------------------------------------------------------------------------------------------------------------

Trying to do the same with list(), as.list(), and unlist() is painful!

test4 <- function() {

aa <- 792 bb <- "Hello one last time"

objectNames <- ls() objectList <- list() for (i in 1:length(objectNames)) { objectList[[objectNames[i]]] <- eval(parse(text = objectNames[i])) }

invisible(objectList) }

out <- test4()

unlist(out)

```



John-R-Wallace-NOAA/JRWToolBox documentation built on Feb. 21, 2020, 2:37 p.m.