我正在使用'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
拋出一個錯誤,這是不必要的,並且省略它拋出一個(至少可以理解的)錯誤,它已被刪去。