Is there a function that returns the corresponding response vector in the model.matrix?

In glmnet (), I have to specify the original X matrix and Y vector (other than lm, where you can specify the model formula). model.matrix () will correctly remove incomplete observations from matrix X, but will not include the answer in the output object. So I will have something like this:

mydf
glmnet(y = mydf$response, x = model.matrix(myformula, mydf)[,-1], ...)

      

When model.matrix removes cases, the y and x dimensions do not match. Is there a function to align data y into x?

+3


source to share


1 answer


Try using model.frame

and model.response

.

> d <- data.frame(y=rnorm(3), x=c(1,NA,2), z=c(NA, NA, 1))
> d
           y  x  z
1 -0.6257260  1 NA
2 -0.4979723 NA NA
3 -1.2233772  2  1
> form <- y~x
> mf <- model.frame(form, data=d)
> model.response(mf)
        1         3
-0.625726 -1.223377
> model.matrix(form, mf)
  (Intercept) x
1           1 1
3           1 2
attr(,"assign")
[1] 0 1

      



I am not familiar with glmnet

, it may be that it is mf

enough just by going through y=mf[1,]

and x=mf[-1,]

.

+2


source







All Articles