Want to solve programming problems and get paid for it? If that sounds interesting to you then contact us.

It seems your original data frame has a factor variable among the predictor variables. So when ever you use model.matrix it does something sensible with this variable; if you pass it directly to predict, it will not know what to do.

newX <- model.matrix(~.-y,data=x_test) fit_test<-predict(fit, newx=newX,s=lambda_min)

You could also have replicated this example with a minimal example, with just a few lines of data ... for example, this setup gives the same error

set.seed(101) dd <- data.frame(y=rnorm(5), a=1:5,b=2:6,c=3:7,d=letters[1:5]) model <- model.matrix(y~., data=dd) n <- nrow(dd) train <- sample(1:n, size=round(0.8*n)) test <- setdiff(1:n,train)