R作用域:不允许函数中使用全局变量 [英] R scoping: disallow global variables in function

查看:80
本文介绍了R作用域:不允许函数中使用全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在R函数中使用了全局变量,是否有任何方法可以发出警告(并失败).我认为这可以节省很多时间,并且可以防止意外行为……例如.

Is there any way to throw a warning (and fail..) if a global variable is used within a R function? I think that is much saver and prevents unintended behaviours...e.g.

sUm <- 10
sum <- function(x,y){
sum = x+y
return(sUm)
}

由于返回"typo",该函数将始终返回10.它应该返回失败,而不是返回sUm的值.

due to the "typo" in return the function will always return 10. Instead of returning the value of sUm it should fail.

推荐答案

我的另一个答案是更多关于可以在函数内部采用的方法.现在,我将提供一些有关定义函数后该怎么做的见解.

My other answer is more about what approach you can take inside your function. Now I'll provide some insight on what to do once your function is defined.

为确保函数在不应该使用的时候不使用全局变量,请使用codetools包.

To ensure that your function is not using global variables when it shouldn't be, use the codetools package.

library(codetools)

sUm <- 10
f <- function(x, y) {
    sum = x + y
    return(sUm)
}

checkUsage(f)

这将打印消息:

<anonymous> local variable ‘sum’ assigned but may not be used (:1)

要查看函数中是否使用了全局变量,可以将findGlobals()函数的输出与全局环境中的变量进行比较.

To see if any global variables were used in your function, you can compare the output of the findGlobals() function with the variables in the global environment.

> findGlobals(f)
[1] "{"  "+"  "="  "return"  "sUm"

> intersect(findGlobals(f), ls(envir=.GlobalEnv))
[1] "sUm"

这说明您可能不应该在f()内部使用全局变量sUm.

That tells you that the global variable sUm was used inside f() when it probably shouldn't have been.

这篇关于R作用域:不允许函数中使用全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆