2017-02-15 63 views
0

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

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抛出一个错误,这是不必要的,并且省略它抛出一个(至少可以理解的)错误,它已被删去。

回答

1

确定为后人:

我改写了功能,使它们具有相同的参数集,以相同的顺序。

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