0

Consider the function with functions below:

f1=function(){
 f3=function() print(a)
 f2=function() {
   print(a)
   a=3
   f3()}
 print(a)
 a=2
 f2()

a=1
f1()
[1] 1
[1] 2
[1] 2

Why does f2() consider f1() its parent environment but f3() does not consider f2() its parent environment? I expect f3() printing 3, set on f2(), rather than 2.
If a variable is defined inside f2(), f3() can not find it:

f1=function(){
 f3=function() print(b)
 f2=function() {
   print(a)
   b=3
   f3()}
 print(a)
 a=2
 f2()

a=1
f1()
[1] 1
[1] 2
Error in print(b) : object 'b' not found 
xm1
  • 1,663
  • 1
  • 17
  • 28

1 Answers1

1

Why does f2() consider f1() its parent environment

Because it is defined inside f1.

but f3() does not consider f2() its parent environment?

Because it is not defined inside f2.

You need to distinguish between containing environment, and parent frame. f2 is the parent frame of f3 in your call. But f1 is its containing environment regardless.

See also What is the difference between parent.frame() and parent.env() in R; how do they differ in call by reference?, and Hadley’s introduction into environments.

Community
  • 1
  • 1
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Tks, @Konrad. Is there a way to call `f3()` setting `f2()` as its parent.environment? – xm1 Apr 19 '17 at 15:09
  • I tried to specify the frame as the enviroment without sucess. – xm1 Apr 19 '17 at 15:20
  • @xm1 Not really, no. You can write `environment(f3) = environment()` inside `f2`. However, this will create *a new copy* of `f3` inside `f2`. For more details it would be helpful to know what you *actually* want to accomplish. – Konrad Rudolph Apr 19 '17 at 15:23
  • as said in Hadley´s site, R does not have dynamic scoping. Tks again. I solved just doing the right thing: passing parameters. :) – xm1 Apr 19 '17 at 17:35