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

和自甴很熟 提交于 2019-12-11 05:09:00

问题


I'm trying to create a function that will, simultaneously, clear the workspace and the memory so that, rather than having to type "rm(list = ls()); gc()", I can type just one function. But rm(list = ls()) doesn't work when it's called from within a function. Why? Is there any way around this?

> # 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"    
> 

回答1:


rm is actually working, however since you're using it inside a function, it only removes all objects pertaining to the environment of that function.

Add envir = .GlobalEnv parameter to both calls:

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

should do it.

I also recommend you take a look at this other question about gc() as i believe it's not a good practice to call it explicitly unless you really need it.



来源:https://stackoverflow.com/questions/46966847/rmlist-ls-doesnt-work-inside-a-function-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!