Although there are some questions about this topic (e.g. this question), none of them answer my particular questions (as far as I could tell anyway).
Suppose I have a function which depends on a lot of parameters. For demonstration purposes I chose 3 parameters:
myfun <- function(x1, x2, x3){
some code containing x1, x2, x3
}
Often the input parameters are already contained in a list
:
xlist <- list(x1 = 1, x2= 2, x3 = 3)
I want to run myfun
with the inputs contained in xlist
like this:
myfun(xlist$x1, xlist$x2, xlist$x3)
However this seems like too big of an effort (because of the high number of parameters).
So I decided to modify myfun
: instead of all the input parameters. It now gets the whole list as one single input: at the beginning of the code I use attach
in order to use the same code as above.
myfun2 <- function(xlist){
attach(xlist)
same code as in myfun containing x1, x2, x3
detach(xlist)
}
I thought that this would be quite a neat solution, but a lot of users advise to not use attach
.
What do you think? Are there any arguments to prefer myfun
over myfun2
?
Thanks in advance.