开发者

run a function with multiple values for more than one arguments that are not the first ones

In R, if I have a function

myfun<-function(ys, T, N, beta, gamma, sigma) {...}

where beta and gamma are scalars.

If I have fixed values for ys, T, N, and sigma, but a vector of values of beta and a vector of values for gamma, is it possible to run myfun each time with every possible combination of values for beta and gamma?

I am considering lapply, but don't know how to specify if the arguments with many values to try are not the first argument in the function and also are not just one argument.

Or do I have to rewrite the function myfun so that lapply or similar ones can apply to it?

Or I have to use loop?

开发者_运维问答

Thanks and regards!


Let's use a handy multi-argument function like dt() as an example. We will ("mult")-supply 2 arguments in "parallel" and ("const")-supply fixed values for the other two. Build a dataframe with expand.grid for the multi-argument lists and then pass it to mapply with appropriate names and use MoreArgs for the remaining arguments;

gamma <- 1:3 
beta <- 1:4
gb.df <-expand.grid(gamma=gamma, beta=beta)
mfun <- dt
mapply ("mfun", x=gb.df$gamma, df=gb.df$beta, MoreArgs=list(ncp=1, log=FALSE) )
    [1] 0.26355595 0.14379745 0.07896827 0.31785177 0.17910975 0.08636815
    [7] 0.34118167 0.19555939 0.08572842 0.35411486 0.20513016 0.08355531


Look at the mapply and Vectorize functions along with expand.grid for the all combinations part.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜