The problem is the environments. Each R function creates an environment for you and both ls
how much rm
act by default in the current environment.
To affect the global environment you have to specify it directly. To do this you can add an environment parameter to the code. I made the change in the first example with a function receiving strings and one receiving arguments with ...
.
Note: remember that in this way the function itself is also deleted. All objects in the global Nvironment are deleted, including other functions you created before in the code.
vec1 <- c(1,2,3)
vec2 <- c(2,3)
a <- 2
b <- 3
environment()
#> <environment: R_GlobalEnv>
test_function <- function() print(environment())
test_function()
#> <environment: 0x2571008>
cleanmem_general <- function(to_keep = c(), target_env = .GlobalEnv){
all_vars <- ls(all.names = T, envir = target_env)
to_remove <- all_vars[which(!(all_vars %in% to_keep))]
rm(list = to_remove, pos = target_env);gc()
}
cleanmem_general(c("vec1", "a"));ls()
#> used (Mb) gc trigger (Mb) max used (Mb)
#> Ncells 486124 26.0 1050760 56.2 676331 36.2
#> Vcells 894859 6.9 8388608 64.0 1820804 13.9
#> [1] "a" "vec1"
vec1 <- c(1,2,3)
vec2 <- c(2,3)
a <- 2
b <- 3
cleanmem_nse <- function(..., target_env = .GlobalEnv){
to_keep <- as.character(substitute(list(...)))[-1]
all_vars <- ls(all.names = T, envir = target_env)
to_remove <- all_vars[which(!(all_vars %in% to_keep))]
rm(list = to_remove, pos = target_env);gc()
}
cleanmem_nse(vec1, a);ls()
#> used (Mb) gc trigger (Mb) max used (Mb)
#> Ncells 486215 26.0 1050760 56.2 676331 36.2
#> Vcells 894943 6.9 8388608 64.0 1820804 13.9
#> [1] "a" "vec1"
Created on 2020-06-15 by the reprex package (v0.3.0)
Thanks for the edition.
– Fabiano Briao