Jacob Colvin
Jacob Colvin

Reputation: 75

R scope rules for nested functions

I am trying to use R's lexical scoping with 2 levels of functions, but the behavior in R 3.0.2 does not seem right.

foo = function() print(ii)
eye_foo = function( ) { 
    ii = 1  # (A)
    foo()
}
eye_foo()   # (B)
ii=2        # (C)
eye_foo()   # (D)

I would expect that (B) would print "1", binding to the variable defined at (A). Instead (B) gives an error message "Error in print(ii) : object 'ii' not found". However, after defining ii at (C) in the global scope, (D) prints "2" ignoring (A) in the process.

Why is (A) being ignored?

Upvotes: 4

Views: 1117

Answers (1)

IRTFM
IRTFM

Reputation: 263301

foo was defined in the global environment. At the time of the first call to eye_foo there was no value for ii to be found in the environment where foo was created. Then you made a value to be found and got the expected results. Simple as that.

> environment(foo)
<environment: R_GlobalEnv>

 ?'function'
 ?globalenv

Generally people avoid this conundrum by passing arguments to functions.

Upvotes: 2

Related Questions