Jill Clover
Jill Clover

Reputation: 2328

How get coefs name from glmnet in R?

I am doing lasso with glmnet in R. I have the lasso coefs out$beta

Input:

x1  0.5744207722
x2 -0.3575682570
x3 -0.0995794334

How can I extract the name of the variables?

Desired output: x1, x2,x3

What I tried

  1. $
  2. as.data.frame
  3. as.matrix

but none of them convert the coefs into a n row 2 columns matrix. They remain as a vector, x1 0.5744207722.

I cannot do it manually. I have more than 1000 variables and more models to run. And I don't won't to write it on my disk, and read it back.

Upvotes: 0

Views: 1240

Answers (1)

alex23lemm
alex23lemm

Reputation: 5675

Based on your input above it seems that you specified a glmnet call with a single lambda value.

In this particular case you can extract the names of the coefficients like this: names(out$beta[, 1][out$beta[, 1] != 0]). Please note that only the names of the non-zero betas are extracted, which makes sense when applying Lasso here since Lasso performs feature reduction.

A minimum reproducible example would be this: out <- glmnet(as.matrix(mtcars[-1]), mtcars[["mpg"]], lambda = 1)

Upvotes: 1

Related Questions