R中包中的全局变量 [英] Global variables in packages in R

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

问题描述

我在R中开发一个包。我有一堆函数,其中一些需要一些全局变量。如何管理包中的全局变量?



我已经阅读了有关环境的一些内容,但我不明白它如何工作,甚至可以去解决问题。

解决方案

通常,全局变量是 邪恶 。为什么他们是邪恶的根本原则是你想要最小化你的包中的互连。这些互连往往会导致函数产生副作用,即它不仅取决于输入参数的结果,而且还取决于某个全局变量的值。特别是当功能数量增加时,这可能很难得到正确和调试。

对于R中的全局变量,请参阅 SO帖子



编辑回应您的评论:
另一种方法可能是传递需要它的功能所需的信息。您可以创建一个包含此信息的新对象:

  token_information = list(token1 =087091287129387,
token2 =UA2329723)

并要求所有需要此信息的函数将其作为参数:

  do_stuff =函数(arg1,arg2,token)
do_stuff(arg1,arg2,token = token_information)

通过这种方式,代码很清楚,函数中需要令牌信息,并且可以调试函数在其自己的。此外,该函数没有副作用,因为它的行为完全由其输入参数决定。典型的用户脚本如下所示:

  token_info = create_token(token1,token2)
do_stuff(arg1,arg2 ,token_info)

我希望这可以让事情变得更加清晰。

I'm developing a package in R. I have a bunch of functions, some of them need some global variables. How do I manage global variables in packages?

I've read something about environment, but I do not understand how it will work, of if this even is the way to go about the things.

解决方案

In general global variables are evil. The underlying principle why they are evil is that you want to minimize the interconnections in your package. These interconnections often cause functions to have side-effects, i.e. it depends not only on the input arguments what the outcome is, but also on the value of some global variable. Especially when the number of functions grows, this can be hard to get right and hell to debug.

For global variables in R see this SO post.

Edit in response to your comment: An alternative could be to just pass around the needed information to the functions that need it. You could create a new object which contains this info:

token_information = list(token1 = "087091287129387",
                         token2 = "UA2329723")

and require all functions that need this information to have it as an argument:

do_stuff = function(arg1, arg2, token)
do_stuff(arg1, arg2, token = token_information)

In this way it is clear from the code that token information is needed in the function, and you can debug the function on its own. Furthermore, the function has no side effects, as its behavior is fully determined by its input arguments. A typical user script would look something like:

token_info = create_token(token1, token2)
do_stuff(arg1, arg2, token_info)

I hope this makes things more clear.

这篇关于R中包中的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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