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