将命名参数列表传递给函数?

时间:2022-08-09 19:13:34

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!

谢谢!

2 个解决方案

#1


47  

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

您的变体list(n=100,params)将创建一个列表,其中第二个元素是参数列表。使用str()来比较列表的结构(n=100,params)和c(list(n=100),params)…

#2


1  

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

c(…)有连锁效应,或者用FP的说法,是一种扁平化效应,所以你可以缩短通话时间;你的代码是:

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)

看起来如果一个列表在任何一点,结果就是一个列表(在这个用例中,这是一个可取的特性)

#1


47  

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

您的变体list(n=100,params)将创建一个列表,其中第二个元素是参数列表。使用str()来比较列表的结构(n=100,params)和c(list(n=100),params)…

#2


1  

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

c(…)有连锁效应,或者用FP的说法,是一种扁平化效应,所以你可以缩短通话时间;你的代码是:

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)

看起来如果一个列表在任何一点,结果就是一个列表(在这个用例中,这是一个可取的特性)