0

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')"

10 Rep
  • 2,217
  • 7
  • 19
  • 33
Ph.D.Student
  • 704
  • 6
  • 27

2 Answers2

2

Use predict instead with argument type="nonzero".

user2974951
  • 9,535
  • 1
  • 17
  • 24
1

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

Flora Grappelli
  • 659
  • 9
  • 26
  • Thank you for your answer, it's work: which(as.vector(coef(fitL) != 0)) [1] 1 77 82 97 126 150 214 267 278 416 522 617 621 701 714 810 822 858 859 [20] 876 886 .... – Ph.D.Student Sep 27 '19 at 09:02