rm(list = ls()) 在函数内部不起作用。为什么?

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

我正在尝试创建一个函数,该函数将同时清除工作区和内存,这样我就不必键入 "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"    
> 

rm 实际上有效,但是由于您在函数内部使用它,它只会删除与该函数环境相关的所有对象。

向两个调用添加 envir = .GlobalEnv 参数:

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

应该这样做。

我还建议您查看 this 关于 gc() 的其他问题,因为我认为除非您 确实 需要,否则显式调用它不是一个好习惯它。