Search code examples
rglmnet

How can I get the coefficients of a glmnet model into a dataframe?


I've trained a glmnet model with caret

pen.params = expand.grid(lambda = exp(seq(-3,3,0.05)) , alpha = 1 )

model.penalized = train(y~.,
                        data = d.train,
                        trControl = fitControl,
                        tuneGrid = pen.params,
                        method = 'glmnet'
                        )

I can plot the coefficients using a variety of tools, but I'd like to have them in a dataframe. I've tried to use broom to extract the coefficients using thetidy, but this only gives me the non-zero coefficients.

Is there an easy way to extract coefficients and penalty parameter from the model and have them as columns in a dataframe?


Solution

  • dfCoef <- data.frame(lambda=model.penalized$finalModel[['lambda']],
              as.matrix(t(model.penalized$finalModel[['beta']])))
    dfCoef[1:10,]
    
    #           lambda          X2           X3          X4         X5
    # s0  0.1608367514 0.000000000  0.000000000 0.000000000 0.00000000
    # s1  0.1465484577 0.000000000  0.000000000 0.000000000 0.01347397
    # s2  0.1335294966 0.000000000  0.000000000 0.000000000 0.02575094
    # s3  0.1216671042 0.000000000  0.000000000 0.000000000 0.03693727
    # s4  0.1108585340 0.000000000  0.000000000 0.000000000 0.04712983
    # s5  0.1010101674 0.000000000  0.000000000 0.000000000 0.05641691
    # s6  0.0920367025 0.000000000  0.000000000 0.000000000 0.06487896
    # s7  0.0838604155 0.000000000  0.000000000 0.000000000 0.07258926
    # s8  0.0764104873 0.000000000 -0.006189269 0.000000000 0.07905622
    # s9  0.0696223902 0.000000000 -0.011967900 0.000000000 0.08493612
    # s10 0.0634373290 0.003340502 -0.016868476 0.000000000 0.09006299
    # ...