Ph.D.Student
Ph.D.Student

Reputation: 726

Error extracting non-zero glmnet coefficients with "which"

I fitted a cox model with glmnet like:

fitL <- glmnet(
  X,
  Y,
  family = "cox",
  alpha = 1,
  lambda = cvL$lambda.min, #cvL obteined with cv.glmnet
  standardize = FALSE,
  thresh = thresh
)

I obtained:

str(coef(fitL) != 0)
Formal class 'lgCMatrix' [package "Matrix"] with 6 slots
  ..@ i       : int [1:24] 0 76 81 96 125 149 213 266 277 415 ...
  ..@ p       : int [1:2] 0 24
  ..@ Dim     : int [1:2] 1000 1
  ..@ Dimnames:List of 2
  .. ..$ : chr [1:1000] "001" "002" "003" "004" ...
  .. ..$ : chr "s0"
  ..@ x       : logi [1:24] TRUE TRUE TRUE TRUE TRUE TRUE ...
  ..@ factors : list()

I would like to extract the non-zero coefficients (i.e. the selected variables), I used "which" and I had this error:

> which (coef (fitL)! = 0) 

Error in base :: which (x, arr.ind, useNames, ...): the 'which' argument must be of logical type

I also used extract.coef function of the coefplot package proposed here. I had this error:

> library (coefplot)
> coefplot :: extract.coef (fitL)

Error in UseMethod (generic = "extract.coef", object = model):    no method for 'extract.coef' applicable for an object of class "c ('coxnet', 'glmnet')"

Upvotes: 0

Views: 532

Answers (2)

Flora Grappelli
Flora Grappelli

Reputation: 679

The object (coef(fitL) != 0) has the class lgCMatrix. Try to use as.vector

Upvotes: 1

user2974951
user2974951

Reputation: 10375

Use predict instead with argument type="nonzero".

Upvotes: 2

Related Questions