xm1
xm1

Reputation: 1765

Variable scope or parent environment

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 

Upvotes: 0

Views: 105

Answers (1)

Konrad Rudolph
Konrad Rudolph

Reputation: 545518

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.

Upvotes: 1

Related Questions