Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R error in glmnet: NA/NaN/Inf in foreign function call

I am trying to create a model using glmnet, (currently using cv to find the lambda value) and I am getting an error NA/NaN/Inf in foreign function call (arg 5). I believe this has something to do with the NA values in my data set, because when I remove all data points with NAs the command runs successfully.

I was under the impression that glmnet can handle NA values. I'm not sure where the error is coming from:

> res <- cv.glmnet(features.mat, as.factor(tmp[,"outcome"]), family="binomial")
Error in lognet(x, is.sparse, ix, jx, y, weights, offset, alpha, nobs,  : 
  NA/NaN/Inf in foreign function call (arg 5)

The dataset looks something like this:

> head(features.mat)
6 x 8 sparse Matrix of class "dgCMatrix"
   a b   c  e  f  g  h i
1  1 1 138 NA NA 15 NA .
4  1 3 171 NA NA 17 NA .
7  1 1 156 NA NA  5 NA .
8  1 4  97 NA NA  7 NA .
9  1 1 219 NA NA 11 NA .
10 1 . 263 NA NA 20 NA .
> head(as.factor(tmp[,"outcome"]))
[1] 0 0 0 0 0 0
Levels: 0 1
like image 384
mgoldwasser Avatar asked Feb 18 '14 15:02

mgoldwasser


2 Answers

It appears that glmnet cannot handle NA values!

like image 100
mgoldwasser Avatar answered Oct 08 '22 23:10

mgoldwasser


Addition: In case that you get this error without having NA's in your dataframe, you probably haven't defined your input matrix with the model.matrix function.

x <- model.matrix( ~ ., Data)

I know it is not the answer to your question but i had the same error as you and found this solution. So it might be helpful for others.

like image 28
Pedrinho Avatar answered Oct 08 '22 22:10

Pedrinho