[R] Lexical scoping is not what I expect

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jun 26 13:35:55 CEST 2013


On 13-06-26 6:57 AM, S Ellison wrote:
>
>
>> -----Original Message-----
>> It may be helpful not to worry about the technical details,
>> just to look at the source code defining the function:  if it
>> is defined in a place where a variable can be seen, it can
>> see that variable.
>
> I too find R's lexical scoping rules straightforward.
> However, I'd say that if your code relies on lexical scoping to find something, you should probably rewrite your code.
>
> The number of times I've seen new R users get unexpected results because they haven't noticed that their function is referencing a parent environment instead of a locally defined variable or argument is past counting.
>
> Of course there are times when it's useful and sensible to have globally defined variables that can be accessed within a function. But they are very rare; as a default, I'd recommend avoiding it if at all possible. If your function needs something from outside, pass it as an argument.
>

I would say the meaning of "probably" in your 2nd sentence depends quite 
a bit on the user.  For beginners, it's "almost certainly".  For people 
who are comfortable with the concept, it's just "maybe".

I would agree that in most cases the only global objects that functions 
should reference are other functions, but small nested functions are 
quite safe, and it's sometimes useful to create functions in a local 
environment so they have persistent memory.

Duncan Murdoch



More information about the R-help mailing list