从函数中删除.GlobalEnv中的对象 [英] Remove objects in .GlobalEnv from within a function
本文介绍了从函数中删除.GlobalEnv中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个函数(CleanEnvir
),该函数基本上调用remove/rm并从.GlobalEnv
中删除某些对象.
I would like to create a function (CleanEnvir
) which basically calls remove/rm and which removes certain objects from .GlobalEnv
.
CleanEnvir <- function(pattern = "tmp"){
rm(list = ls()[grep("tmp", ls())], envir = globalenv())
}
keep <- 1
tmp.to.be.removed <- 0
ls()
## does not work
CleanEnvir()
ls()
## does work
rm(list = ls()[grep("tmp", ls())], envir = globalenv())
ls()
推荐答案
ls()
需要在正确的位置查找.默认情况下,它会在当前帧中查找CleanEnvir
函数的当前帧,因此只能在原始帧中找到"pattern"
.
ls()
needs to look in the correct place. By default it looks in the current frame, that of the function CleanEnvir
in your case and hence was only finding "pattern"
in your original.
CleanEnvir <- function(pattern = "tmp") {
objs <- ls(pos = ".GlobalEnv")
rm(list = objs[grep("tmp", objs)], pos = ".GlobalEnv")
}
哪个给:
> CleanEnvir <- function(pattern = "tmp") {
+ objs <- ls(pos = ".GlobalEnv")
+ rm(list = objs[grep("tmp", objs)], pos = ".GlobalEnv")
+ }
> ls()
[1] "CleanEnvir" "foo" "keep"
[4] "tmp.to.be.removed"
> CleanEnvir()
> ls()
[1] "CleanEnvir" "foo" "keep"
这篇关于从函数中删除.GlobalEnv中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文