rm(list = ls())在函数内部不起作用.为什么? [英] rm(list = ls()) doesn't work inside a function. Why?

查看:294
本文介绍了rm(list = ls())在函数内部不起作用.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个函数,该函数将同时清除工作区和内存,以便不必键入"rm(list = ls()); gc()",而只键入一个功能.但是从函数内部调用rm(list = ls())无效.为什么?有什么办法解决吗?

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

推荐答案

rm实际上正在工作,但是由于您是在函数内部使用它,因此它仅删除与该函数环境有关的所有对象.

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.

在两个调用中都添加envir = .GlobalEnv参数:

Add envir = .GlobalEnv parameter to both calls:

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

应该这样做.

我还建议您查看这个关于gc()的问题,因为我认为除非您确实需要它,否则明确地调用它不是一个好习惯.

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.

这篇关于rm(list = ls())在函数内部不起作用.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆