1

I am new to R and try to understand the environments. According to that question an environment is called for each function call. Hence, I expected that search() shows me that new environment created by a new function call. Indeed, it is not appearing in the demo code bellow and also the variable x, which should be in the parent environment, is not found.

a<-function(){ # should create a further environment
  print(search()) # does not include any "new" environment, just global and packages
  #print(x) #not working but should be in the parent environment
}

b<-function(){ #should create an environment
  x<-2
  a()
}
b()
user3579222
  • 1,103
  • 11
  • 28

1 Answers1

2

You implicitly ask two questions: why isn't an environment shown by search(), and why isn't x visible in function a().

The first is easiest: search() only shows environments that have been added to the search list using attach(). There are many other environments.

For the other question, you can see the currently active environment by calling environment(). You can see its parent, by calling parent.env(environment()), and follow the chain all the way back to the end of the chain at the empty environment.

If you do that in a call to a(), you'll see that the active environment contains nothing, because there are no local variables in that function. Its parent is the global environment, because that's where a() was created. The parent of the global environment is the next entry in the search list, and earlier parents go back through the search list to the base environment, whose parent is the empty environment.

You expected the environment of b() to show up in there somewhere, but it doesn't. b() is a caller of a(), but has nothing to do with a()'s definition.

user2554330
  • 37,248
  • 4
  • 43
  • 90