As justmarkham points out, you can construct the design matrix x
using model.matrix
. Note that you'll want to exclude the intercept, since glmnet includes one by default. You may also want to change the default contrast function, which by default leaves out one level of the each factor (treatment coding). But because of the lasso penalty, this is no longer necessary for identifiability, and in fact makes interpretation of the selected variables more complicated. To do this, set
contr.Dummy <- function(contrasts, ...){
conT <- contr.treatment(contrasts=FALSE, ...)
conT
}
options(contrasts=c(ordered='contr.Dummy', unordered='contr.Dummy'))
Now, whatever levels of a factor are selected, you can think of it as suggesting that these specific levels matter, versus all the omitted levels. In machine learning, I have seen this coding referred to as one-hot encoding.
Assuming that g4
has K
levels, the type.multinomial="grouped"
option specifies that the features of x
will all enter the model simultaneously for each of the K
linear predictors, as opposed to having the linear predictor for each class (in general) having its own features. glmnet
does not (currently?) support grouped-type penalties of predictors (the x
matrix). The package grplasso
does, but is written in pure R, so is slower than glmnet
, but you could give that a try.