Search code examples
rglmnet

Error in lambda when running ridge


I am running the following code but keep getting an error message. The code is from the ISLR website.

library(ISLR)
Hitters=na.omit(Hitters)
x=model.matrix(Salary~.,Hitters)[,-1]
y=Hitters$Salary
library(glmnet)
ridge.mod=glmnet(x,y,alpha=0,lambda=grid)

Error message:

Error in lambda < 0 : comparison (3) is possible only for atomic and list types

I would really appreciate any help. Thanks!


Solution

  • Your problem is here:

    ridge.mod=glmnet(x,y,alpha=0,lambda=grid)
    

    grid is a name of an R function (try '?grid'), but glmnet is expecting vector of lambda values.

    If you run glmnet without providing a lambda sequence, the glmnet library uses its own heuristic to choose lambdas:

    ridge.mod=glmnet(x,y,alpha=0)
    

    You can also provide your own sequence:

    ridge.mod=glmnet(x,y,alpha=0, lambda=seq(10, 1000, 1))
    

    but glmnet help advises against it.

    lambda A user supplied lambda sequence. Typical usage is to have the program compute its own lambda sequence based on nlambda and lambda.min.ratio. Supplying a value of lambda overrides this. WARNING: use with care. Avoid supplying a single value for lambda (for predictions after CV use predict() instead). Supply instead a decreasing sequence of lambda values. glmnet relies on its warms starts for speed, and its often faster to fit a whole path than compute a single fit.

    (Note that 'seq(10, 1000, 1)' above is just an example to show the correct syntax.)