Can we have more error (messages)?
Asked Answered
S

3

3

Is there a way, in R, to pop up an error message if a function uses a variable not declared in the body of the function: 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"

Shine answered 26/1, 2010 at 16:51 Comment(1)
That's usually called a 'feature' :) It would be the same in C or C++, by the way, with scoping going from the local function to the next layer, usually global.Gristmill
E
18

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’.

Eyla answered 26/1, 2010 at 17:40 Comment(0)
C
5

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.

Creeps answered 26/1, 2010 at 17:28 Comment(1)
+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.Gristmill
B
1

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)
}
Brewster answered 26/1, 2010 at 17:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.