Search code examples
rlanguage-concepts

Can we have more error (messages)?


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"


Solution

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