Michael and Sarah:

1. Actually the original claim -- that R will search the global environment
if it does not find a free variable in the function environment -- is not
strictly true. It will search the function's enclosure and then on up the
tree of enclosures. In this case, the enclosure was the global environment,
but that is not always the case.

2. Sarah has answered one interpretation of your question. Another might be
-- how can you do things to throw an error when free variables are
encountered in a function. A qualified answer -- qualified, because there
are probably some clever ways to set this up that I can't and won't try to
think of -- is that you can't: you are defeating R's functional programming
paradigm by requesting such behavior. Or to put it another way: don't
do/expect this. Follow Sarah's recommendation instead.

Cheers,
Bert


On Thu, Sep 12, 2013 at 2:08 PM, Sarah Goslee <sarah.goslee@gmail.com>wrote:

> Hi,
>
> You need to specify that a is an argument to the function:
>
> On Thu, Sep 12, 2013 at 3:56 PM, Gang Peng <michael.gang.peng@gmail.com>
> wrote:
> > For example:
> >
> > a <- 1
> >
> > f <- function(b){
> >     return(a+b)
> > }
> >
>
> f <- function(b, a) {
>     return(a+b)
> }
>
> > when we call function f(2), r will search the local environment first, if
> > it cannot find a, it will search global environment, and return 3. How to
> > avoid r searching the global environment and return an error when we call
> > this function?
>
> The function will now give an error if a is not specified.
>
> Sarah
>
> --
> Sarah Goslee
> http://www.functionaldiversity.org
>
> ______________________________________________
> 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.
>



-- 

Bert Gunter
Genentech Nonclinical Biostatistics

Internal Contact Info:
Phone: 467-7374
Website:
http://pharmadevelopment.roche.com/index/pdb/pdb-functional-groups/pdb-biostatistics/pdb-ncb-home.htm

	[[alternative HTML version deleted]]

