Passing list of named parameters to function?

前端 未结 2 1598
野趣味
野趣味 2020-12-05 06:18

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

makeSample <- function(n,dist,params)
values <- m         


        
相关标签:
2条回答
  • 2020-12-05 06:52

    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) ...

    0 讨论(0)
  • 2020-12-05 07:02

    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)

    0 讨论(0)
提交回复
热议问题