On 7/2/2009 2:17 PM, Steve Lianoglou wrote:
Hi,

I was wondering if I could get R to warn me, or give me a rude awakening somehow, if I'm accessing a variable that is out of my function's scope.

For example, often times I'm creating a function as I'm testing it in the REPL, copying and pasting between both.

As a simple example, I might end up with a function like:

f <- function(a, b) {
   a + b.test
}

Where b.test was defined in my workspace as I'm mucking about in the REPL, but "clearly" I should have written:

f <- function(a,b) {
   a + b
}

I could go on for a while in my session w/o noticing the problem (since b.test is in my global env), and unbeknownst to me, my function will keep accessing the "b.test" variable when I really want it to work on the "b" var that I'm passing in to it.

Is there some setting or someway I can get R to warn me that "b.test" is being accessed outside the scope of my function?

Not really, but the codetools package can analyze your functions and tell you which ones do things like that. For example,

> f <- function(a, b) {
+    a + b.test
+ }
> checkUsage(f)
<anonymous>: no visible binding for global variable ‘b.test’

or

> checkUsageEnv(globalenv())
f: no visible binding for global variable ‘b.test’

This is normally used in the package test code, but you can use it on individual functions or environments if you want.

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