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?
attach() function in R Language is used to access the variables present in the data framework without calling the data frame. Parameters: data: data frame.
The ATTACH command enables an application to specify the instance at which instance-level commands (CREATE DATABASE and FORCE APPLICATION, for example) are to be executed. This instance can be the current instance, another instance on the same workstation, or an instance on a remote workstation.
The detach() function removes a database or object library/package from the search path. It can also detach objects combined by attach() like DataFrame, series, and so on.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With