Search code examples
rgarbage-collectionwrapper

rm and Garbage Collection Wrapper


How would I make a function named rm2 that takes in an unknown number of objects, removes them, and then runs the gc()?

I have tried a could things but cannot figure it out.

rm2 <- function(...){
  #files <- list(...)
  #files <- list(deparse(substitute(...)))
  #rm(list = files)
  rm(...)
  capture.output(gc(),file='NUL')
}

I would appreciate it.

Also, lets try to not bring up the gc() complaints. I find that it does help to free up RAM to my host OS :)


Solution

  • A simple option is to do as rm itself does and use the ... from the matched call (from match.call). This gives a list of symbols, which I then convert to a character vector using sapply. This vector is then passed to rm as argument list. Finally we just return the output from gc:

    rm2 <- function(...) {
      dots <- match.call(expand.dots = FALSE)$...
      dots <- sapply(dots, as.character)
      rm(list = dots, envir = globalenv())
      gc()
    }
    
    > ls()
    [1] "pred" "reg4" "rm2"  "tenv" "x"    "y"   
    > rm2(x, y)
             used (Mb) gc trigger (Mb) max used (Mb)
    Ncells 226670 12.2     467875   25   350000 18.7
    Vcells 357248  2.8     905753    7   867363  6.7
    > ls()
    [1] "pred" "reg4" "rm2"  "tenv"