tags:

views:

143

answers:

3

Is there a way, in R, to pop up an error message if a function uses a variable not declared: i.e, i want someone to flag this type of functions

aha<-function(p){
  return(p+n)
}

see; if there happens to be a "n" variable lying somewhere, aha(p=2) will give me an "answer" since R will just take "n" from that mysterious place called the "environment"

+1  A: 

Writing R codes to check other R code is going to be tricky. You'd have to find a way to determine which bits of code were variable declarations, and then try and work out whether they'd already been declared within the function. EDIT: The previous statement would have been true, but as Aniko pointed out, the hard work has already been done in the codetools package.

One related thing that may be useful to you is to force a variable to be taken from the function itself (rather than from an enclosing environment).

This modified version of your function will always fail, since n is not declared.

aha <- function(p) 
{ 
   n <- get("n", inherits=FALSE)
   return(p+n)
}
Richie Cotton
+4  A: 

Richie's suggestion is very good.

I would just add that you should consider creating unit test cases that would run in a clean R environment. That will also eliminate the concern about global variables and ensures that your functions behave the way that they should. You might want to consider using RUnit for this. I have my test suite scheduled to run every night in a new environment using RScript, and that's very effective and catching any kind of scope issues, etc.

Shane
+1 for clean environment -- that's what I use 'r' from littler for all the time, and there is Rscript if you're on the one platform we don't support for littler.
Dirk Eddelbuettel
+7  A: 

If you want to detect such potential problems during the code-writing phase and not during run-time, then the codetools package is your friend.

library(codetools)
aha<-function(p){ 
  return(p+n) 
}

#check a specific function:
checkUsage(aha) 

#check all loaded functions:
checkUsageEnv(.GlobalEnv)

These will tell you that no visible binding for global variable ‘n’.

Aniko