R语言中的变量冲突 [英] Conflict of variables in R language

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

问题描述

我有一个 R 脚本,它采用 R 的其他脚本并以这种方式操作它们,并执行它们的代码.我的脚本使用了一些变量(显然),当其他脚本使用通用变量名时,我会陷入混乱.我希望我可以像在胶囊中一样执行另一个脚本,这样重合的变量就不会相互影响.

I have a script of R which takes other scripts of R and manipulates them in such a way, and also executes their code. My script uses some variables (obviously), and when the other scripts use a common variable name, I get in a mess. I wish I could execute the other script like in a capsule, such that the coinciding variables do not affect each other.

我一直在阅读有关环境的书,并进行了很多尝试,但我没有理解它们的真正含义.

I have been reading about environments, and have made a lot of trials, but I don't catch their real meaning.

示例:

script1.txt
___________
i=sample(10:20,1)

script2.txt
___________
i=sample(10:20,1) 

myscript.txt
___________
other.script = c("script1.txt", "script2.txt")
for( i in 1:2 ) {
    source(other.script[i])
}
i==2

我希望每个变量i"在不影响其他变量的情况下完成其职责(特别是我脚本中的那个,我不太关心其他变量).

I wish each variable "i" does its duty without affecting the other ones (specially the one in myscript, I don't care much about the other ones).

推荐答案

解决此问题的最佳方法是创建一组函数,将脚本捕获的功能分割开来.每个函数都在自己的环境中执行,防止变量相互干扰.理想情况下,函数不应太长,比如 10-20 行或代码.一个比调用这些函数来完成工作更大的脚本.如果您正确地执行此操作,您的脚本可能会简短而切题.我通常将这些函数存储在一个或多个脚本文件中,以供需要它们的脚本source使用.您甚至可以将它们包裹在一个包裹中.

The best way to deal with this is to create a set of functions which cut up the functionality captured by your scripts. Each function is executed in its own environment, preventing variables getting in each others way. Ideally, functions shouldn't be too long, say 10-20 lines or code. A larger script than calls these functions to get stuff done. If you do this correctly, your scripts can be short and to the point. I usually store these functions in one or more script files, ready to be sourceed by scripts needing them. You could even wrap them in a package.

按照您希望的脚本排序方式,所有变量都是全局的,即可以在整个程序中访问.一般来说,应该像瘟疫一样避免全局变量.这正是因为您的问题关注的是:如何防止变量相互干扰.就像我说的,抽象成函数或对象是防止这种情况发生的方法.有关全局变量等的更多信息可以在此处找到:

The way you want to order your script, all variables are global, i.e. accessible throughout the whole program. In general, global variables should be avoided like the plague. This is precisely because of what your question focuses on: how do I keep variables from interfering with each other. Like I said, abstraction into functions or objects is the way to keep this from happening. More information on global variables and such can be found there:

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

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