[英]minimize a multivariate function in R with constraints
I am trying to minimize a function, S.residuum
, in R with some constraints我正在尝试最小化 R 中的函数S.residuum
,但有一些限制
S.residuum<- function(w, stdv, corr) {
intermed<-0
for (i in 1:length(stdvv)) {
intermed =intermed+residuum(w,stdvv,corr.mat,i)
}
return(intermed)
}
where w
is a vector with the length 6. The constraints look as follows:其中w
是长度为 6 的向量。 约束如下所示:
0.03 <= w1 <= 0.27
0.03 <= w2 <= 0.27
0.20 <= w3 <= 0.91
0.01 <= w4 <= 0.1
0.01 <= w5 <= 0.1
0.01 <= w6 <= 0.1
So far I was able to implement it:到目前为止,我能够实现它:
nlminb(c(1,1,1,1,1,1),S.residuum,hessian = NULL,
lower=c(0.03,0.03,0.2,0.01,0.01), upper=c(0.27,0.27,0.91,0.1,0.1)),
where c(1,1,1,1,1,1)
are the initial values.其中c(1,1,1,1,1,1)
是初始值。
However, I have 2 other constraints.但是,我还有 2 个其他限制。 I wrote the first one as a functions:我把第一个写成函数:
nequal <- function(w,stdv, corr) {
intermed<-0
for (j in 1:length(stdvv)) {
for (i in 1:length(stdvv)) {
intermed =intermed+ w[[i]] * w[[j]] * stdv[[i]] * stdv[[j]] * corr[[i]][[j]]
}
}
intermed=sqrt(intermed)
},
where stdv
is a vector and corr
is a matrix.其中stdv
是向量, corr
是矩阵。 The following constraints should be fulfilled:应满足以下约束条件:
1) nequal <=0.75
2) w1+w2+w3+w4+w5+w6=1
can someone say to me how can I do it in R?有人可以对我说我怎么能在 R 中做到这一点? Thanks!谢谢!
You can use the function solnp in the package Rsolnp .您可以使用Rsolnp包中的函数solnp 。 The code looks like this:代码如下所示:
library(Rsolnp)
# Inequality constraint
nequal <- function(w) {
intermed <- 0
for (j in 1:length(stdvv)) {
for (i in 1:length(stdvv)) {
intermed = intermed + w[[i]] * w[[j]] * stdvv[[i]] * stdvv[[j]] * corr.mat[[i]][[j]]
}
}
sqrt(intermed)
}
# Equality constraint
equal <- function(w) {
w[[1]]+w[[2]]+w[[3]]+w[[4]]+w[[5]]+w[[6]]
}
# Minimization with constraints
min <- solnp(c(0., 0., 0., 0., 0., 0.),
S.residuum,
eqfun = equal,
eqB = 1,
ineqfun = nequal,
ineqLB = 0,
ineqUB = 0.075,
LB = c(0.03, 0.03, 0.2, 0.01, 0.01, 0.01),
UB = c(0.27, 0.27, 0.91, 0.1, 0.1, 0.1))
我在这里找到了constrOptim()
,它对我来说效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.