You can use the package fined :
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)
This gives the same thing:
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 you limit the coefficients x1 and x2 positive, they become zero (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
source share