Can we have more error (messages)?

给你一囗甜甜゛ 提交于 2019-12-04 11:54:44

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

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.

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