Skip to content

Function does not see variables outside the function

7 messages · Zhong-Yuan Zhang, Rui Barradas, Carl Witthoft +2 more

#
Hello,

I believe the answer is no. Functions will first look in their 
environment, and then in the parent frame, i.e., outside the function.

Hope this helps,

Rui Barradas

Em 05-11-2013 10:42, Zhong-Yuan Zhang escreveu:
#
Why would you want to impose this restriction?  Perhaps if you explain what
you are trying to do, we can suggest approaches that will satisfy your
specific needs.
(note- one can always redefine whatever variables are to be "excluded." E.g.
to keep the body of a function from referring to 'foo' in the calling
environment, just add the line 'foo<-NA' inside the function)


Zhong-Yuan Zhang wrote

            
--
View this message in context: http://r.789695.n4.nabble.com/Function-does-not-see-variables-outside-the-function-tp4679762p4679768.html
Sent from the R help mailing list archive at Nabble.com.
#
On 05/11/2013 12:25, Rui Barradas wrote:
That is not correct.  The scoping rule when evaluatiing a function is to 
look first in the evaluation frame, then the function's environment (see 
?environment).  The parent frame is not part of the scope (unless part 
of the environment).

You can set a function's environment to emptyenv(): then there will be 
no search outside the function.  As that includes no search for any of 
the functions implementing R itself, only very simple functions will be 
self-contained.

You can control the search by setting a function's environment.  Most 
likely that will achieve what you want to do (but have not told us).

  
    
#
Dear Zhong-Yuan Zhang,

R is lexically scoped. Pretending that you're using a different programming
language is probably a bad idea. 

The findGlobals() function in the codetools package, which is part of the
standard R distribution, can help you locate references to global variables
(and functions) in a function. For example,
[1] "a" "g"
[1] "{"  "<-" "g"
[1] "g"

I hope this helps,
 John