watchtower
watchtower

Reputation: 4298

Deleting objects from environment in R

I am reading Hadley's Advanced R. In chapter 8, he says that we can remove an object from an environment by using rm(). However, I am still able to see the object after removing it.

Here's my code:

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)

As we can see above, ideally, I'd have expected exists("c", envir = e) to return FALSE.

Any thoughts? Thanks in advance.

Upvotes: 3

Views: 4024

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99331

From help(exists):

If inherits is TRUE and a value is not found for x in the specified environment, the enclosing frames of the environment are searched until the name x is encountered.

Be careful when naming your variables. You have a conflict with the base function c(). Since inherits = TRUE is the default, the enclosing environments are searched and in this case the base function c() is found, which produces the TRUE result. Therefore, to search only the environment e and then quit, use inherits = FALSE.

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

Upvotes: 3

oglox
oglox

Reputation: 67

It seems that your problem is that e$c has a NULL value try instead using

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

Upvotes: 1

Related Questions