0

I am reading Hadley Wickham's Advanced R - Chapter 8 on Environment.

Recently, I encountered a situation where I accidentally created and deleted an object c which also exists in R_GlobalEnv. Here's my thread: Deleting objects from environment in R So, I thought whether there is any way I can know ALL the environment with which an object is (or could be) attached.

I searched this topic on SO, and came across How to get environment of a variable in R thread, where one of the experts has created a function that works only for R_GlobalEnv and not for every environment.

However, on that thread, the expert says that

This only checks environments created within .GlobalEnv. I'm sure you can work out how to extend it to search across more environments though if you need.

I am wondering how to do this.

Here's my code:

rm(list=ls()) 
e<- new.env()
parent.env(e) #Should be Global Env.
environmentName(e) #Shows Blank

Here's my modified function from that thread:

getEnvMod <- function(x) {
  xobj <- deparse(substitute(x))
  gobjects <- ls(envir=.GlobalEnv)
  envirs <- gobjects[sapply(gobjects, function(x) is.environment(get(x)))]
  envirs <- c('.GlobalEnv', envirs)
  xin <- sapply(envirs, function(e) xobj %in% ls(base::get(x = x,envir = e))) #Modified this line
  envirs[xin] 
}

When I run this function using:

getEnvMod("a")

I get the error message: Error in as.environment(pos) : no item called "base::get(x = x, envir = e)" on the search list

I get above message although the object exists.

exists("a",envir = e)
[1] TRUE

get(x="a",envir = e)
[1] 1

I have two questions:

Question 1: why does environmentName(e) return "" ? Shouldn't it return e?

Question 2: I am unsure how I can list all environments that have a particular object. I'd appreciate any thoughts.

Community
  • 1
  • 1
watchtower
  • 4,140
  • 14
  • 50
  • 92
  • For 1), suppose I do `myEnv <- new.env(); ename <- function(e) environmentName(e)`. Should `ename(myEnv)` return `e`? – Hong Ooi Mar 11 '17 at 07:59
  • @Hong -Thank you. Yes, it must return the environment name. I checked your code, and it returns `""`. – watchtower Mar 11 '17 at 08:00

0 Answers0