Passing list of named parameters to function?

R

R Problem Overview


I want to write a little function to generate samples from appropriate distributions, something like:

makeSample <- function(n,dist,params)
values <- makeSample(100,"unif",list(min=0,max=10))
values <- makeSample(100,"norm",list(mean=0,sd=1))

Most of the code works, but I'm having problems figuring out how to pass the named parameters for each distribution. For example:

params <- list(min=0, max=1)
runif(n=100,min=0,max=1) # works
do.call(runif,list(n=100,min=0,max=1)) # works
do.call(runif,list(n=100,params)) # doesn't work

I'm guessing I'm missing a little wrapper function somewhere but can't figure it out.

Thanks!

R Solutions


Solution 1 - R

Almost there: try

do.call(runif,c(list(n=100),params)) 

Your variant, list(n=100,params) makes a list where the second element is your list of parameters. Use str() to compare the structure of list(n=100,params) and c(list(n=100),params) ...

Solution 2 - R

c(...) has a concatenating effect, or in FP parlance, a flattening effect, so you can shorten the call; your code would be:

params <- list(min=0, max=1)
do.call(runif, c(n=100, params))

Try the following comparison:

params = list(min=0, max=1)
str(c(n=100, min=0, max=1))
str(list(n=100, min=0, max=1))
str(c(list(n=100),params))
str(c(n=100,params))

Looks like if a list is in there at any point, the result is a list ( which is a desirable feature in this use case)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjkeirsteadView Question on Stackoverflow
Solution 1 - RBen BolkerView Answer on Stackoverflow
Solution 2 - RDarren BishopView Answer on Stackoverflow