Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to isolate a function

Tags:

r

How can I ensure that when a function is called it is not allowed to grab variables from the global environment?

I would like the following code to give me an error. The reason is because I might have mistyped z (I wanted to type y).

z <- 10
temp <- function(x,y) {
        y <- y + 2
        return(x+z)
}
> temp(2,1)
[1] 12

I'm guessing the answer has to do with environments, but I haven't understood those yet.

Is there a way to make my desired behavior default (e.g. by setting an option)?

like image 390
Xu Wang Avatar asked Nov 02 '11 02:11

Xu Wang


3 Answers

> library(codetools)
> checkUsage(temp)
<anonymous>: no visible binding for global variable 'z'

The function doesn't change, so no need to check it each time it's used. findGlobals is more general, and a little more cryptic. Something like

Filter(Negate(is.null), eapply(.GlobalEnv, function(elt) {
    if (is.function(elt))
        findGlobals(elt)
}))

could visit all functions in an environment, but if there are several functions then maybe it's time to think about writing a package (it's not that hard).

like image 159
Martin Morgan Avatar answered Oct 05 '22 07:10

Martin Morgan


environment(temp) = baseenv()

See also http://cran.r-project.org/doc/manuals/R-lang.html#Scope-of-variables and ?environment.

like image 25
John Colby Avatar answered Oct 05 '22 07:10

John Colby


environment(fun) = parent.env(environment(fun))

(I'm using 'fun' in place of your function name 'temp' for clarity)

This will remove the "workspace" environment (.GlobalEnv) from the search path and leave everything else (eg all packages).

like image 38
c-urchin Avatar answered Oct 05 '22 07:10

c-urchin