R 中是否提供更严格的错误报告?
在 PHP 中,我们可以执行 error_reporting(E_ALL)
或 error_reporting(E_ALL|E_STRICT)
来获得有关可疑代码的警告。在 g++ 中,您可以提供 -Wall
(和其他标志)来对代码进行更多检查。 R中有类似的吗?
作为一个具体的例子,我将一段代码重构为一些函数。在其中一个函数中,我有这样一行:
if(nm %in% fields$non_numeric)...
很久以后,我意识到我忽略了将 fields
添加到参数列表,但 R 并没有抱怨未定义的变量。
In PHP we can do error_reporting(E_ALL)
or error_reporting(E_ALL|E_STRICT)
to have warnings about suspicious code. In g++ you can supply -Wall
(and other flags) to get more checking of your code. Is there some similar in R?
As a specific example, I was refactoring a block of code into some functions. In one of those functions I had this line:
if(nm %in% fields$non_numeric)...
Much later I realized that I had overlooked adding fields
to the parameter list, but R did not complain about an undefined variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
(作为答案而不是评论发布)
?codetools::checkUsage
怎么样(codetools
是一个内置包)...?(Posting as an answer rather than a comment)
How about
?codetools::checkUsage
(codetools
is a built-in package) ... ?这并不是真正的答案,我只是忍不住展示如何显式声明全局变量。 @Ben Bolker 应该发表他的评论作为答案。
为了避免看到全局变量,您可以在一个环境“上”调用一个函数 - 它将能够看到所有标准函数等(
mean
等),但看不到您放入其中的任何内容全局环境:然后获取全局只是从
.GlobalEnv
中检索它:它会像这样使用
并被调用,
我个人不会这样做,但如果你习惯了 PHP 它可能会感觉。
This is not really an answer, I just can't resist showing how you could declare globals explicitly. @Ben Bolker should post his comment as the Answer.
To avoiding seeing globals, you can take a function "up" one environment -- it'll be able to see all the standard functions and such (
mean
, etc), but not anything you put in the global environment:Then getting a global is just retrieving it from
.GlobalEnv
:And it would be used like
And called like
I personally wouldn't go for this but if you're used to PHP it might make sense.
总而言之,确实没有正确的答案:正如 Owen 和 gsk3 指出的那样,如果变量不在本地范围内,R 函数将使用全局变量。在某些情况下这可能是可取的,那么如何指出“错误”呢?
checkUsage() 不会执行 R 内置错误检查不会执行的任何操作(在本例中)。 checkUsageEnv(.GlobalEnv) 是检查辅助函数文件的有用方法(并且可能非常适合作为 svn 或 git 的预挂钩;或者作为自动构建过程的一部分)。
我认为重构时最好的解决方案是:从一开始就将所有全局代码移动到一个函数(例如称之为
main()
),然后唯一的全局代码将是调用该函数。先这样做,然后开始提取函数等。Summing up, there is really no correct answer: as Owen and gsk3 point out, R functions will use globals if a variable is not in the local scope. This may be desirable in some situations, so how could the "error" be pointed out?
checkUsage() does nothing that R's built-in error-checking does not (in this case). checkUsageEnv(.GlobalEnv) is a useful way to check a file of helper functions (and might be great as a pre-hook for svn or git; or as part of an automated build process).
I feel the best solution when refactoring is: at the very start to move all global code to a function (e.g. call it
main()
) and then the only global code would be to call that function. Do this first, then start extracting functions, etc.