Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attach() inside function

Tags:

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?

like image 936
statistician_in_training Avatar asked Apr 26 '11 23:04

statistician_in_training


People also ask

What does attach () do in R?

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.

What is attach () command?

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.

What is detach () in R?

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.


2 Answers

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.

like image 145
Roman Luštrik Avatar answered Oct 04 '22 23:10

Roman Luštrik


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 } 
like image 23
Jean-Luc Jannink Avatar answered Oct 04 '22 22:10

Jean-Luc Jannink