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?
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 likewhich will yield identical result, but is tidier.
Easiest way to solve scope problems like this is usually to try something simple out:
As you can see, R is picking up the global attribute
a
here.It's almost always a good idea to avoid using
attach
anddetach
wherever possible -- scope ends up being tricky to handle (incidentally, it's also best to avoid naming variablesc
-- 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: