Can we have more error (messages)?

亡梦爱人 提交于 2019-12-21 20:18:25

问题


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"


回答1:


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




回答2:


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:


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)
}


来源:https://stackoverflow.com/questions/2140972/can-we-have-more-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!