[R] How to avoid searching variables in global environment

William Dunlap wdunlap at tibco.com
Thu Sep 12 23:29:57 CEST 2013


If you want to find out if you've forgotten to make 'a' an argument
you can use codetools::findGlobals(func) to list the names that don't
refer to something already defined in the 'func':
  > fun <- function(b) a + b
  > library(codetools)
  > findGlobals(fun)
  [1] "+" "a"
You need to filter out things defined in some attached package (like the "+"
from the base package).  I think that when you run 'R CMD check' on a
package this sort of check is made on the functions in the package.
findGlobals does not run the function to make its checks, it just looks at
the function.

A kludgy way to get an error message instead of having the function silently
use something from .GlobalEnv is to make the environment of the function
the parent of .GlobalEnv
   >  a <- 1000
   > environment(fun) <- parent.env(globalenv())
   > fun(7)
   Error in fun(7) : object 'a' not found
Since this is a run-time check it will not find problems in branches of the
code that are not run.  The parent environment of .GlobalEnv changes
every time you attach or detach a package.  For production code you will
want to use a package - the namespace mechanism and the check command
will take care of most of this sort of problem.

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of Sarah Goslee
> Sent: Thursday, September 12, 2013 2:09 PM
> To: Gang Peng
> Cc: r-help at r-project.org
> Subject: Re: [R] How to avoid searching variables in global environment
> 
> 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 at 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 at 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.



More information about the R-help mailing list