Skip to content

Commit

Permalink
Considering a 'clean_env' function to clear the global environment of…
Browse files Browse the repository at this point in the history
… all objects except user-specified objects
  • Loading branch information
njlyon0 committed Jul 31, 2024
1 parent c09be75 commit 2b74388
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions dev/clean_env.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@



# Testing 'clean_env' function


# Make some objects
x <- list()
y <- "Aaa"
z <- 123

# Define function
clean_env <- function(except, collect_garbage = TRUE){

# Error for supplied 'except' that is not a character vector
if(length(except) != 0){
if(is.character(except) != TRUE)
stop("'except' values must be provided as a character vector")
}

# Warning for malformed garbage collect entry
if(is.logical(collect_garbage) != TRUE){
warning("'collect_garbage' must be logical. Defaulting to FALSE")
collect_garbage <- FALSE }

# Identify objects to remove (all of them if no exceptions are specified)
if(length(except) != 0){

# Identify non-exception objects
trash <- generics::setdiff(x = ls(), y = except)

# Otherwise flag all object names for removal
} else { trash <- ls() }

# Clear environment (except for the other argument of the function)
rm(list = generics::setdiff(x = trash, y = "collect_garbage"))

# If indicated, collect garbage
if(collect_garbage == TRUE){ gc(verbose = FALSE) }
}

clean_env(except = c("clean_env", "x"), collect_garbage = T)

0 comments on commit 2b74388

Please sign in to comment.