我正在尝试创建一个同时清除工作区和内存的函数,这样就不必键入“rm(list = ls()); gc()”,我只能输入一个功能。但是当从函数内部调用时,rm(list = ls())不起作用。为什么?有没有办法解决这个问题?
> # 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"
>
答案 0 :(得分:3)
rm
实际上正在工作,但是由于您在函数内部使用它,它只会删除与该函数环境相关的所有对象。
为两个调用添加envir = .GlobalEnv
参数:
rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv)
应该这样做。
我还建议您查看有关gc()的this其他问题,因为我认为除非您真的需要它,否则明确调用它并不是一个好习惯