attach() inside function

放肆的年华 提交于 2019-11-28 09:01:45

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.

Jean-Luc Jannink

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
}
Noah

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.

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

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