R Global Function to Clear Workspace and Dump Storage

758 views Asked by At

I was hoping to make a global function that would clear my workspace and dump my memory. I called my function "cleaner" and want it to execute the following code:

remove(list = ls())
gc()

I tried making the function in the global environment but when I run it, the console just prints the text of the function. In my function file to be sourced:

cleaner <- function(){
    remove(list = ls())
    gc()
    #I tried adding return(invisible()) to see if that helped but no luck
}

cleaner()

Even when I make the function in the script I want it to run (cutting out any potential errors with sourcing), the storage dump seems to work, but it still doesn't clear the workspace.

enter image description here

1

There are 1 answers

1
fcdt On BEST ANSWER

Two thoughts about this: Your code does not delete all objects, to also remove the hidden ones use

rm(list = ls(all.names = TRUE))

There is also the command gctorture() which provokes garbage collection on (nearly) every memory allocation (as the man page said). It's intended for R developers to ferret out memory protection bugs:

cleaner <- function(){
    # Turn it on
    gctorture(TRUE)

    # Clear workspace
    rm(list = ls(all.names = TRUE, envir=sys.frame(-1)),
       envir = sys.frame(-1))

    # Turn it off (important or it gets very slow)
    gctorture(FALSE)
}

If this procedure is used within a function, there is the following problem: Since the function has its own stack frame, only the objects within this stack frame are deleted. They still exist outside. Therefore, it must be specified separately with sys.frame(-1) that only the higher-level stack frame should be considered. The variables are then only deleted within the function that calls cleaner() and in cleaner itself when the function is exited.

But this also means that the function may only be called from the top level in order to function correctly (you can use sys.frames() which lists all higher-level stack frames to build something that also avoids this problem if really necessary)