R linear model with constraints

*爱你&永不变心* 提交于 2019-12-30 10:37:29

问题


I want to fit a linear model

y ~ a_1 * x_1 + ... + a_n * x_n

with parameter constraints

a_1,...,a_n >=0 

and

a_1 + ... + a_n <= 1 

in R.

Is there an elegant and fast way to do that and without using solve.QP of the quadprog package. It would be wonderful if a short but detailed use case would be outlined for a proposed solution.


回答1:


You can use constrOptim with cost function least square and contraints defined such that ui %*% a >= ci.

Suppose n=3. You want constraints such as:

 a1         >=  0
     a2     >=  0
         a3 >=  0
-a1 -a2 -a3 >= -1

Thus you have to provide constrOptim the following parameters:

ui = rbind(c(1,0,0),
           c(0,1,0),
           c(0,0,1),
           c(-1,-1,-1))

ci = c(0,0,0,-1)

Set also explicitely grad=NULL in constrOptim if you do not use the gradient.

Hope it helps.



来源:https://stackoverflow.com/questions/28383685/r-linear-model-with-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!