[R] Passing a large amount of parameters to a function

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Wed Aug 24 09:55:57 CEST 2011


You could use something like the following:

paramsList <- list(p1 = 1:10, p2 = -5:5, p3 = 5, p4 = 8)
params <- unlist(as.relistable(paramsList))

myFunc <- function (params) {
     params <- relist(params, skeleton = paramsList)
     p1 <- params$p1
     p2 <- params$p2
     p3 <- params$p3
     p4 <- params$p4
     ...
}

For another example have a look at the online help file of relist().

I hope it helps.

Best,
Dimitris


On 8/24/2011 9:28 AM, Eran Eidinger wrote:
> Hello,
>
> I have a function with a long list of parameters (of different types,
> numeric and string)
>
> myFunc<-function(p1, p2, p3, p4, p5...etc)
> {
>     do.something(p1,p2,....)
> }
>
> I want to loop over this to provide a different set of parameters to the
> list every time.
>
> for (ii in 1:N)
> {
>     myFunc(p1(ii), p2(ii),....etc)
> }
>
> I would like to simplify the notation and use some kind of structure, maybe
> a list or dataframe.
> However when I try, for example, the following:
>
> params = data.frame(cbind(p1=c(1,2,3), p2=5, p3=c(3,2,1)))
> myFunc<-function(params)
> {
>     attach(params)
>     do.something(p1,p2,....)
>     detach(params)
> }
> for (ii in 1:N)
> {
>     myFunc(params[ii,])
> }
>
>
> do.something fails because p1, p2,... are now factors, and i have to
> as.numeric() or as.char() each parameter before applying mathematical
> operators (such as simple multiplication).
> This defeats the purpose of simplifying the code.
>
> Is there any decent, simple way of doing this?
> Can I unfactor a row of a data.frame? or a list?
> (BTW, "as.numeric()" won't work since some of the parameters are strings,
> same goes for stringsAsFactors in data.frame)
>
> Thanks,
> Eran
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list