[R] Function does not see variables outside the function

Prof Brian Ripley ripley at stats.ox.ac.uk
Tue Nov 5 13:59:29 CET 2013


On 05/11/2013 12:25, Rui Barradas wrote:
> 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.

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).

>
> Hope this helps,
>
> Rui Barradas
>
> Em 05-11-2013 10:42, Zhong-Yuan Zhang escreveu:
>> Dear experts:
>>
>>       In MATLAB, functions cannot see variables outside the
>>
>> functions.  However, in R, the functions can do that. Is there
>>
>> any settings that can disable this ability of functions?
>>
>>       Many thanks for your kind help.
>>
>>       Best Regards Always.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list