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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to