I want to force some independent variables in the elastic net regression model. There is an error when using penalty.factor in the cva.glmnet() function. Any suggestions and comments are appreciated.
# --------------- import data
# outcome: am
# ten predictors: mpg+cyl+disp+hp+drat+wt+qsec+vs+gear+carb
mydata<-mtcars
mydata$am<-factor(mydata$am,levels=c(0,1),labels=c("no","yes"))
mydata$gear<-factor(mydata$gear,levels=c(3,4,5),labels=c("level3","level4","level5"))
str(mydata)
'data.frame': 32 obs. of 11 variables:
$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
$ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
$ disp: num 160 160 108 258 360 ...
$ hp : num 110 110 93 110 175 105 245 62 95 123 ...
$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
$ wt : num 2.62 2.88 2.32 3.21 3.44 ...
$ qsec: num 16.5 17 18.6 19.4 17 ...
$ vs : num 0 0 1 1 0 1 0 1 1 1 ...
$ am : Factor w/ 2 levels "no","yes": 2 2 2 1 1 1 1 1 1 1 ...
$ gear: Factor w/ 3 levels "level3","level4",..: 2 2 2 1 1 1 1 2 2 2 ...
$ carb: num 4 4 1 1 2 1 4 2 2 4 ...
# --------------- do elastic net cross-validation for alpha and lambda simultaneously
# works
library("glmnetUtils")
set.seed(12345)
cvfit<-cva.glmnet(am~mpg+cyl+disp+hp+drat+wt+qsec+vs+gear+carb,
family="binomial",
alpha=seq(from=0,to=1,by=0.05),
nfolds=10,
data=mydata)
# --------------- force three variables of "cyl", "disp", "hp" in the final model
# does not work
set.seed(12345)
cvfit<-cva.glmnet(am~mpg+cyl+disp+hp+drat+wt+qsec+vs+gear+carb,
family="binomial",
penalty.factor=c(0,0,0,1,1,1,1,1,1,1),
alpha=seq(from=0,to=1,by=0.05),
nfolds=10,
data=mydata)
Error in approx(lambda, seq(lambda), sfrac) :
need at least two non-NA values to interpolate