Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

r - Passing list of named parameters to function?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...