Search code examples
rglmnet

R: glmnet: saving and using glmnet models from a list


I can make a number of different models using glmnet. I then saved the models in a list so I could use this list of models in future use.

library(glmnet)
x1=matrix(rnorm(100*20),100,20)
y1=matrix(rnorm(100*3),100,3)
fit1m=glmnet(x1,y1,family="mgaussian")

x2=matrix(rnorm(100*20),100,20)
y2=matrix(rnorm(100*3),100,3)
fit2m=glmnet(x2,y2,family="mgaussian")


x3=matrix(rnorm(100*20),100,20)
y3=matrix(rnorm(100*3),100,3)
fit3m=glmnet(x3,y3,family="mgaussian")


listmodels <-list(fit1m,fit2m,fit3m)
listmodels

However when I tried to retrieve a model from this list, I got a class error

fit1 <- listmodels[1]
fit1


xnew=matrix(rnorm(100*20),100,20)
pred1 <- as.data.frame(predict(fit1,newx=xnew),s="lambda.min")
pred1

What do I need to do to make the models in the list work correctly? Thank you for any help.


Solution

  • If we extract the list element correctly, it will work i.e. 'listmodels[1]' is still a list, we need to use 'listmodels[[1]]' to extract the element

    fit1 <- listmodels[[1]]
    
    xnew=matrix(rnorm(100*20),100,20)
    pred1 <- as.data.frame(predict(fit1,newx=xnew),s="lambda.min")
    pred1
    

    If we want to do this to all the list elements, we can loop over the list (lapply) and do the same process

    lapply(listmodels, function(x) as.data.frame(predict(x, 
            newx = matrix(rnorm(100*20), 100, 20)), s = "lambda.min"))