簡體   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