简体   繁体   中英

R glmnet returns error: (list) object cannot be coerced to type 'double'

I am trying to create a function that just does the ridge regression using the glmnet function and returns the coefficients. The function takes in x,y values.

myfun <- function(x,y)
{
  data<-cbind(x,y)
  model<-model.matrix(y~., data=data)
  ridgedata = model[,-1]
  train<- sample(1:dim(ridgedata)[1], round(0.8*dim(ridgedata)[1]))
  test<- setdiff(1:dim(ridgedata)[1],train)
  grid =10^ seq (10,-2, length =100)
  ridge_model<-glmnet(x[train,],y[train],alpha=0, lambda =grid)
  return(coef(ridge_model))
}

But i get the following error when i run the glmnet function:

Error in elnet(x, is.sparse, ix, jx, y, weights, offset, type.gaussian,  : 
  (list) object cannot be coerced to type 'double'

in the elnet function, the code corresponding to coercion seems to be

"weights = as.double(weights)"

and it seems to be a vector of 1s. But i don't see why thats causing the error...

This is my function call:

mydata <- read.csv("regress.csv")
x<- mydata[,1:4]
y<- mydata[,5]
myfun(x,y)

I am not sure what is causing the error. Any suggestions would be helpful.

You get that error because you are providing a data.frame as x to glmnet when it requires a matrix. Looking at the code, you created a model.matrix and that should be the input:

myfun <- function(x,y)
{
  data<-cbind(x,y)
  model<-model.matrix(y~., data=data)
  ridgedata = model[,-1]
  n= nrow(ridgedata)
  train<- sample(n, round(0.8*n))
  test<- setdiff(1:n,train)
  grid =10^ seq (10,-2, length =100)
  # bug is here
  ridge_model<-glmnet(ridgedata[train,],y[train],alpha=0, lambda =grid)
  return(coef(ridge_model))
}

head(myfun(mtcars[,-1],mtcars[,1]))
6 x 100 sparse Matrix of class "dgCMatrix"
   [[ suppressing 100 column names ‘s0’, ‘s1’, ‘s2’ ... ]]
                                                                   
(Intercept)  1.997692e+01  1.997692e+01  1.997692e+01  1.997692e+01
cyl         -1.794456e-09 -2.372165e-09 -3.135862e-09 -4.145425e-09
disp        -2.549069e-11 -3.369719e-11 -4.454570e-11 -5.888679e-11
hp          -5.048989e-11 -6.674466e-11 -8.823252e-11 -1.166382e-10
drat         4.829898e-09  6.384841e-09  8.440384e-09  1.115769e-08
wt          -3.313208e-09 -4.379866e-09 -5.789924e-09 -7.653939e-09

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM