0

我希望创建一个全局函数来清除我的工作空间并转储我的内存。我将我的函数称为“cleaner”并希望它执行以下代码:

remove(list = ls())
gc()

我尝试在全局环境中创建函数,但是当我运行它时,控制台只打印函数的文本。在我要获取的函数文件中:

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

cleaner()

即使我在我希望它运行的脚本中创建函数(消除任何潜在的采购错误),存储转储似乎也可以工作,但它仍然没有清除工作区。

在此处输入图像描述

4

1 回答 1

0

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)

于 2020-07-14T18:37:05.670 回答