Search code examples
rgarbage-collectionworkspace

rm(list = ls()) doesn't work inside a function. Why?


I'm trying to create a function that will, simultaneously, clear the workspace and the memory so that, rather than having to type "rm(list = ls()); gc()", I can type just one function. But rm(list = ls()) doesn't work when it's called from within a function. Why? Is there any way around this?

> # Let's create an object
> x = 0
> ls()
[1] "x"
> 
> # This works fine:
> rm(list = ls()); gc()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 269975 14.5     592000 31.7   427012 22.9
Vcells 474745  3.7    1023718  7.9   808322  6.2
> ls()
character(0)
> 
> ## But if I try to create a function to do exactly the same thing, it doesn't work
> # Creating the object again
> x = 0
> ls()
[1] "x"
> 
> #Here's the function (notice that I have to exclude the function name from the 
# list argument or the function would remove itself):
> clear = function(list = ls()[-which(ls() == "clear")]){
+   rm(list = list); gc()
+ }
> ls()
[1] "clear" "x"    
> 

Solution

  • rm is actually working, however since you're using it inside a function, it only removes all objects pertaining to the environment of that function.

    Add envir = .GlobalEnv parameter to both calls:

    rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv)
    

    should do it.

    I also recommend you take a look at this other question about gc() as i believe it's not a good practice to call it explicitly unless you really need it.