attach() inside function

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.


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.


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
}

Tags:

R

Scoping