Conflict of variables in R language

不问归期 提交于 2019-12-11 01:49:29

问题


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.

Example:

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 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).


回答1:


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:

  • Global and local variables in R
  • Global variables in R



回答2:


You are looking for sys.source. You were on the right track, you need to create an environment and then run the script inside that environment.

other.script = c("script1.txt", "script2.txt")
for( i in 1:2 ) {
  env<-new.env(parent = baseenv())
  sys.source(other.script[i],env)
  print(get('i',env)) # prints the value of i
}
i==2 # TRUE


来源:https://stackoverflow.com/questions/12750923/conflict-of-variables-in-r-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!