Can we have more errors (messages)?

Is there a way in R to display an error message if a function uses a variable is not declared in the body of the function: ie, I want someone to mark this type of function

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

cm; if there is an "n" variable somewhere, aha (p = 2) will give me an "answer", because R will simply take "n" from a mysterious place called the "environment"

+3
source share
3 answers

If you want to detect such potential problems at the stage of writing code, and not at runtime, 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) 

This will tell you that no visible binding for global variable 'n' .

+18
source

Richie's offer is very good.

I would just add that you should consider creating unit test cases that will run in a clean environment R. This will also eliminate the problem of global variables and ensure that your functions behave as they should. You may consider using RUnit . I have my own test suite, which is planned to run every night in a new environment using RScript, and it is very effective and catches any problems with the scope, etc.

+5
source

Writing R codes to verify another R code will be difficult. You need to find a way to determine which bits of code were variable declarations, and then try to find out if they were already declared inside the function. EDIT: The previous statement would be true, but, as Aniko noted, the hard work was already done in the codetools package.

One related thing that may be useful to you is to make the variable be taken from the function itself (and not from the environment).

This modified version of your function always fails because n not declared.

 aha <- function(p) { n <- get("n", inherits=FALSE) return(p+n) } 
+1
source

All Articles