回复 第5楼 的 mengchen:多谢老兄!你一说我就明白了。不过当我模仿上面的案例写下面代码的时候,出了一点问题:
fr <- function(x) {
x1=x[1]
x2=x[2]
x3=x[3]
x4=x[4]
x5=x[5]
x6=x[6]
x7=x[7]
-coeff[1]*x1^0.5-coeff[2]*x2^0.5-coeff[3]*x3^0.5-coeff[4]*x4^0.5
-coeff[5]*x5^0.5-coeff[6]*x6^0.5-coeff[7]*x7^0.5
}
# starting point
coeff=c(66.170577,120.462855,210.470447,220.402163,335.550576,620.334902,7.355208)
theta = rep(1,7)
buget.constraint=6000
ui = rbind(rep(-1,7), #x1+x2+...+xn<=buget.constraint
diag(1,7) # xi>=0, i = 1,2,...,7
)
ci = c(-budget.constraint,rep(0,7))
test.start = ui %*% theta - ci
opt = constrOptim(c(1,1,1,1,1,1,1),theta, fr, grad=NULL, ui, ci)
R无法运行constrOptim函数,报错如下:
“错误于ui %*% theta : 需要数值/复数矩阵/矢量参数”;
奇怪的是,如果我改变fr函数的写法如下:
fr2 <- function(xx) {
-crossprod(coeff,xx^0.5)
}
# starting point
theta = rep(1,n.seg)
test.start = ui %*% theta - ci
opt = constrOptim(theta, fr2, grad=NULL, ui, ci)
在R运行成功。上面两个代码的唯一区别是函数fr和fr2,我不知道为什么。再次感谢帮助!