R 范围:禁止在函数中使用全局变量 [英] R scoping: disallow global variables in function

查看:18
本文介绍了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)
}

由于返回错字",函数将始终返回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)

这将打印消息:

<代码><匿名>局部变量'sum'已分配但不能使用(: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"

这告诉您全局变量 sUmf() 中使用了,而它可能不应该使用.

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

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

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