繁体   English   中英

在R中将参数传递给nloptr

[英]Passing arguments to nloptr in r

我正在使用'nloptr'优化r中的一个简单函数,并且很难将参数传递给目标函数。 这是我正在使用的代码:

require("nloptr")

Correl <- matrix(c(1,-.3,-.3,1), nrow=2, ncol=2)
Wghts <- c(.01,.99)
floor <- .035
expret <- c(.05,.02)
pf.return <- function(r, x, threshold=0){

return(r * x - threshold)
}

pf.vol <- function(x, C){

return(sqrt(x %*% C %*% x))
}

res <- nloptr(x0=Wghts,eval_f = pf.vol,eval_g_ineq=pf.return,opts=list(algorithm="NLOPT_GN_ISRES"), x=Wghts,C=Correl)

(我知道我在这里缺少参数,但是我想突出显示一个我不理解的行为)运行此命令会产生以下错误:

Error in .checkfunargs(eval_f, arglist, "eval_f") : x' passed to (...) in 'nloptr' but this is not required in the eval_f function.

只是为了看看会发生什么,我可以尝试在没有x参数的情况下运行它:

res <- nloptr(x0=Wghts,eval_f = pf.vol,eval_g_ineq=pf.return,opts=list(algorithm="NLOPT_GN_ISRES"), C=Correl)

给出错误:

Error in .checkfunargs(eval_g_ineq, arglist, "eval_g_ineq") : eval_g_ineq requires argument 'x' but this has not been passed to the 'nloptr' function.

因此,包含x会引发不必要的错误,而忽略x则会引发已被忽略的错误(至少是可以理解的)。

后代还可以:

我重写了函数,以便它们具有相同的参数集,并且顺序相同。

我也省略了x=Wghts位,因为这是我要搜索的参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM