attach() inside function

与世无争的帅哥 提交于 2019-11-27 02:40:33

问题


I'd like to give a params argument to a function and then attach it so that I can use a instead of params$a everytime I refer to the list element a.

run.simulation<-function(model,params){
attach(params)
#
# Use elements of params as parameters in a simulation
detach(params)
}

Is there a problem with this? If I have defined a global variable named c and have also defined an element named c of the list "params" , whose value would be used after the attach command?


回答1:


Noah has already pointed out that using attach is a bad idea, even though you see it in some examples and books. There is a way around. You can use "local attach" that's called with. In Noah's dummy example, this would look like

with(params, print(a))

which will yield identical result, but is tidier.




回答2:


Another possibility is:

run.simulation <- function(model, params){
    # Assume params is a list of parameters from 
    # "params <- list(name1=value1, name2=value2, etc.)"
    for (v in 1:length(params)) assign(names(params)[v], params[[v]])
    # Use elements of params as parameters in a simulation
}



回答3:


Easiest way to solve scope problems like this is usually to try something simple out:

a = 1
params = c()
params$a = 2
myfun <- function(params) {
  attach(params)
  print(a)
  detach(params)
}
myfun(params)

The following object(s) are masked _by_ .GlobalEnv:

a

# [1] 1

As you can see, R is picking up the global attribute a here.

It's almost always a good idea to avoid using attach and detach wherever possible -- scope ends up being tricky to handle (incidentally, it's also best to avoid naming variables c -- R will often figure out what you're referring to, but there are so many other letters out there, why risk it?). In addition, I find code using attach/detach almost impossible to decipher.




回答4:


Jean-Luc's answer helped me immensely for a case that I had a data.frame Dat instead of the list as specified in the OP:

for (v in 1:ncol(Dat)) assign(names(Dat)[v], Dat[,v])



来源:https://stackoverflow.com/questions/5797797/attach-inside-function

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