我正在尝试使用一些约束来最小化函数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)
}
其中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
到目前为止,我能够实现它:
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)),
其中c(1,1,1,1,1,1)
是初始值。
但是,我有另外两个限制。我把第一个写成函数:
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)
},
其中stdv
是向量,corr
是矩阵。应满足以下约束条件:
1) nequal <=0.75
2) w1+w2+w3+w4+w5+w6=1
有人可以对我说我怎么能在R中做到这一点? 谢谢!
答案 0 :(得分:1)
您可以使用 Rsolnp 包中的 solnp 功能。代码如下所示:
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))
答案 1 :(得分:0)
我发现constrOptim()
here,对我来说很好。