从R中删除环境中的对象

时间:2017-03-11 05:45:38

标签: r environment-variables

我正在阅读Hadley的高级R.在第8章中,他说我们可以使用rm()从环境中删除对象。但是,我仍然可以在删除它后看到该对象。

这是我的代码:

e<- new.env()
e$a<-1
e$b<-2
e$.a<-3
e$c<-4
ls(e,all.names = TRUE)

#remove the object c
rm("c",envir = e)
ls(e,all.names = TRUE) #Doesn't exist here

#does the variable exist?
exists("c",envir = e) #Shows TRUE. Why is this?
exists("m",envir = e) #FALSE

ls(e,all.names = TRUE)
ls(e)

正如我们上面所见,理想情况下,我希望exists("c", envir = e)返回FALSE

有什么想法?提前谢谢。

2 个答案:

答案 0 :(得分:3)

来自help(exists)

  

如果inheritsTRUE并且在指定环境中找不到x的值,则会搜索环境的封闭框架,直到遇到名称x为止

命名变量时要小心。您与基本函数c()发生冲突。由于inherits = TRUE是默认值,因此会搜索封闭环境,在这种情况下会找到基函数c(),从而生成TRUE结果。因此,要仅搜索环境e然后退出,请使用inherits = FALSE

exists("c", envir = e, inherits = FALSE)
# [1] FALSE

答案 1 :(得分:1)

看来你的问题是e $ c有一个NULL值而不是使用

exists("c", envir = e, inherits = FALSE)
相关问题