regression - R - Force certain parameter to have positive coefficient in lm() -


i know how constrain parameters in lm() have positive coefficient. there few packages or functions (e.g. display) can make coefficient , intercept positive.

for instance, in example, force x1 , x2 has positive coefficients.

    x1=c(na,rnorm(99)*10)     x2=c(na,na,rnorm(98)*10)     x3=rnorm(100)*10     y=sin(x1)+cos(x2)-x3+rnorm(100)      lm(y~x1+x2+x3)      call:       lm(formula = y ~ x1 + x2 + x3)            coefficients:       (intercept)           x1           x2           x3       -0.06278      0.02261     -0.02233     -0.99626 

i have tried function nnnpls() in package'nnls', can control coefficient sign easily. unfortunately can't use due issues nas in data function doesn't allow na.

i saw function glmc() can used apply constrains couldn't working.

could let me know should do?

you can use package penalized:

set.seed(1)  x1=c(na,rnorm(99)*10) x2=c(na,na,rnorm(98)*10) x3=rnorm(100)*10 y=sin(x1)+cos(x2)-x3+rnorm(100) df <- data.frame(x1,x2,x3,y)  lm(y~x1+x2+x3, data=df) #call: #lm(formula = y ~ x1 + x2 + x3, data = df) # #coefficients: #(intercept)           x1           x2           x3   #   -0.02438     -0.01735     -0.02030     -0.98203   

this gives same:

library(penalized)  mod1 <- penalized(y, ~ x1 + x2 + x3, ~1,                    lambda1=0, lambda2=0, positive = false, data=na.omit(df)) coef(mod1) #(intercept)          x1          x2          x3  #-0.02438357 -0.01734856 -0.02030120 -0.98202831  

if constraint coefficients of x1 , x2 positive, become 0 (as expected):

mod2 <- penalized(y, ~ x1 + x2 + x3, ~1,                    lambda1=0, lambda2=0, positive = c(t, t, f), data=na.omit(df)) coef(mod2) #(intercept)          x3  #-0.03922266 -0.98011223  

Comments

Popular posts from this blog

javascript - Wordpress slider, not displayed 100% width -

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -