[R] findGlobals on apply

Duncan Murdoch murdoch at stats.uwo.ca
Tue Apr 8 13:14:08 CEST 2008


Christophe Genolini wrote:
>>> f <- function(x){apply(x,2,mean)}
>>> findGlobals(f)
>>>       
>> mean is a global variable, so findGlobals gets it right. 
>>     
> That sound strange to me: a "variable" is something that vary... mean 
> does not vary. maen will ge an argument that is a line of x and will 
> make some calculous on it, that is the comportement of a function.
> Of course, mean is an argument of an other function, but I do not think 
> this is a reason good enouth to say that mean is a variable.
>   

findGlobals doesn't try to tell what mean is; it's just reporting on how 
you've used it.  Your usage means that the interpreter will treat it as 
a variable, getting a copy of its value and passing it as an argument to 
apply.  (That's an oversimplification, of course:  it's very unlikely 
that an actual copy will be made, but it will act as if one was made.)

> Furthemore, I use findGlobals to detect some typo. In
>
> f <- function(myObject){return(mObject^2)}
>
> findGlobals will detect that mObject is a global so I know there is a 
> typo somewhere.
> Considering mean as a globals do not let us use findGlobals this way.
>
>   

You can still use it to detect that kind of typo, but you need a second 
step where you check whether the globals exist in the environment of the 
function or not.  That test won't be perfect either:  it will miss cases 
where you meant to type a local variable, but by mistake typed the name 
of some global.  Most uses of mean as a variable would fall into that 
category; unfortunately (?) apply means some of them are legitimate.

I think the best you'll ever be able to do is to get some suggestions of 
errors, with both false positives and false negatives.  If there were 
cases where some usage was definitely an error, the parser would 
probably catch it.

Duncan Murdoch


> Christophe
>
> ______________________________________________
> 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