Can we have more error (messages)?

2019-04-10 21:23发布

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"

3条回答
来,给爷笑一个
2楼-- · 2019-04-10 21:49

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.

查看更多
一夜七次
3楼-- · 2019-04-10 22:06

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)
}
查看更多
▲ chillily
4楼-- · 2019-04-10 22:11

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

查看更多
登录 后发表回答