【问题标题】:Deleting objects from environment in R从R中的环境中删除对象
【发布时间】:2017-08-01 14:11:30
【问题描述】:

我正在阅读 Hadley 的 Advanced 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

有什么想法吗?提前致谢。

【问题讨论】:

  • 如果使用“C”、“t”、“df”也会存在问题。 R中的所有函数名称。

标签: r environment-variables


【解决方案1】:

来自help(exists)

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

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

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

【讨论】:

    【解决方案2】:

    您的问题似乎是 e$c 有一个 NULL 值尝试使用

    exists("c", envir = e, inherits = FALSE)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多