Search code examples
rregressionglmnetlasso-regression

Plotting a LASSO model with "mtcars" dataset in R


I have recently been made aware of LASSO. As it looks a bit complicated I tried to find an example using mtcars. The following code produces a plot of the independent variables:

library("glmnet")
lasso <- glmnet(as.matrix(mtcars[-1]), mtcars[,1], standardize=TRUE, alpha =1)
plot(lasso)

It does so however without showing which line is which variable.

This explains it, but I cannot figure out which part of the code I need.

This source is a bit easier to read but does not provide the plot code.

Can someone help me figure out which variable is which line?


Solution

  • Use plot(lasso, label = TRUE). Then check rownames(lasso$beta). The i-th variable is labeled by numerical value i in the plot. For a quicker loopup, you can do make a table:

    setNames(rownames(lasso$beta), 1:nrow(lasso$beta))
    

    You probably did not realize that you can check ?plot.glmnet. Or probably you've checked ?plot but found nothing there. Yes, looking for documentation of a generic function on some methods is not straightforward.

    The package vignette, either the old version or the latest version, also covers this labeling issue.