Skip to main content
v2026.11,986 entries · CC-BY 4.0

glmnet in R: Install, Fit and Cross-Validate Lasso

How to install glmnet in R, fit lasso and elastic-net models with cv.glmnet, and read the sparse coefficient output, from the official vignette.

Written and maintained by CASRAI Editorial Board

Published

On this page

glmnet is an R package that fits lasso, ridge and elastic-net regularized generalized linear models along an entire path of penalty values, and its companion cv.glmnet() picks the penalty by cross-validation. This page is for researchers and analysts who need to install glmnet in R, run it on a predictor matrix, and read the output correctly. Commands below follow the package’s official introductory vignette (read 2026-11-11).

Ask CASRAI · free to tryQuestion about this guide? Ask CASRAI answers with linked sources. 2 free questions a day, no account.

Ask your first question freeSubscribe

What glmnet is used for in research

glmnet’s CRAN title is "Lasso and Elastic-Net Regularized Generalized Linear Models." It is used when a model has many candidate predictors relative to the sample (see high-dimensional data) and an ordinary fit would overfit. The penalty shrinks coefficients, and with the lasso penalty some are set exactly to zero, which performs variable selection. For the statistical idea behind the penalty, see the CASRAI guide to elastic net regression and the comparison ridge vs lasso regression.

Per the CRAN description, glmnet fits the lasso or elastic-net path for linear, logistic, multinomial, Poisson and Cox models, plus multiple-response Gaussian and grouped multinomial models. The family argument can also be a GLM family object. The algorithm is cyclical coordinate descent, computed path-wise.

glmnet R: the package is R, with other-language ports

Searches for "glmnet r" refer to the R package, which is the reference implementation. The vignette states that a MATLAB version is maintained by Junyang Qian and a Python version by B. Balakumar, and describes both as a few versions behind the R package.

The penalty, in one line

glmnet minimizes (1/N) Σ wi ℓ(yi, β0 + βTxi) + λ[(1 − α)‖β‖22/2 + α‖β‖1], where α is between 0 and 1. The default α = 1 is the lasso and α = 0 is ridge regression; values between give an elastic net.

Install or access (official source only)

glmnet is distributed on CRAN, the Comprehensive R Archive Network. As of 2026-11-11 the CRAN page lists version 5.2, published 2026-10-28, under the GPL-2 licence. It requires R 3.6.0 or later and the Matrix package (1.0-6 or later), contains compiled code, and lists C++17 as a system requirement. The package homepage is glmnet.stanford.edu; the maintainer listed on CRAN is Trevor Hastie.

install.packages("glmnet", repos = "https://cran.us.r-project.org")
library(glmnet)

Loading the package prints a message such as "Loaded glmnet 5.2". Because the package compiles C++ code, a machine without a C++ toolchain may install from source slowly or fail; see Troubleshooting below.

Step-by-step: fit, cross-validate and predict

The steps use the example data bundled with the package, so they run as written. This is the sequence from the official vignette.

  1. Load the example data. data(QuickStartExample), then x <- QuickStartExample$x and y <- QuickStartExample$y. glmnet takes a predictor matrix x and a response y, not a formula.
  2. Fit the path. fit <- glmnet(x, y). The default family is Gaussian and the default is the lasso (alpha = 1).
  3. Inspect the path. plot(fit) draws coefficient paths against the L1 norm; plot(fit, label = TRUE) annotates the variables. print(fit) lists, for each lambda, the number of nonzero coefficients (Df), the percent deviance explained (%Dev) and the lambda value.
  4. Extract coefficients at a chosen penalty. coef(fit, s = 0.1). Note the argument is s, not lambda.
  5. Predict. predict(fit, newx = nx, s = c(0.1, 0.05)), where nx is a new predictor matrix.
  6. Choose the penalty by cross-validation. cvfit <- cv.glmnet(x, y), then plot(cvfit).
  7. Use the selected model. coef(cvfit, s = "lambda.min") and predict(cvfit, newx = x[1:5,], s = "lambda.min").

For a binary outcome, the vignette’s example is cv.glmnet(x, y, family = "binomial", type.measure = "class"). For background on how folds work, see cross-validation in statistics.

Output and how to read it

Function or object What it returns Point to check
glmnet(x, y) A fitted path; by default 100 lambda values, stopping early if %Dev barely changes Fewer than 100 lambdas in print(fit) is normal
plot(fit) Coefficient paths against the L1 norm Use label = TRUE to identify variables
coef(fit, s = ...) A sparse matrix (dgCMatrix) A "." means the coefficient is exactly zero; wrap in as.matrix() for a dense view
predict(fit, newx, s = ...) Predictions at the requested penalties Pass s, not lambda
cv.glmnet(x, y) Cross-validated error along the path Default fold count and measure can be changed with nfolds and type.measure
cvfit$lambda.min The lambda with minimum mean cross-validated error Lowest cross-validated error
cvfit$lambda.1se The most regularized model whose error is within one standard error of the minimum Sparser; this is what coef(cvfit) uses if you omit s

lambda.min versus lambda.1se

The two cross-validated choices answer different questions. lambda.min minimizes the mean cross-validated error. lambda.1se is the most regularized model within one standard error of that minimum. Because coef(cvfit) and predict(cvfit) default to lambda.1se when s is omitted, results can differ from a colleague’s who typed s = "lambda.min". State which one you used when reporting.

Standardization

standardize = TRUE is the default, so predictors are standardized internally, but coefficients are always returned on the original scale. For the Gaussian family, y is also standardized to compute the lambda sequence, and the coefficients are returned unstandardized.

Common arguments

  • alpha: elastic-net mixing, for example glmnet(x, y, alpha = 0.2, weights = wts, nlambda = 20).
  • weights and nlambda: observation weights and the number of lambda values.
  • penalty.factor: a separate penalty multiplier for each coefficient; lower.limits constrains coefficients from below.
  • nfolds (for example nfolds = 20) and type.measure (for example "mse") in cv.glmnet.

Comparing alpha values fairly

cv.glmnet chooses lambda for one alpha at a time. To compare alpha values, the vignette recommends supplying your own folds with foldid and reusing the same assignment, for example cv.glmnet(x, y, foldid = foldid, alpha = 0.5). Otherwise random fold differences are confounded with the alpha effect.

Further official vignettes cover the regularized Cox model, GLM family functions, and the relaxed lasso (the relax option refits the active set without penalty, per the CRAN description).

Troubleshooting

  • Installation from source fails. The package needs a C++17 compiler (CRAN system requirement) and R 3.6.0 or later. Check the R and compiler versions before anything else.
  • Input shape. The vignette’s interface takes a predictor matrix x and a response y; build the matrix from your data before calling glmnet().
  • Coefficients print as dots. That is the sparse format; a dot is an exact zero. Use as.matrix(coef(fit, s = 0.1)) for a dense table.
  • Wrong argument name in coef() or predict(). The vignette notes these functions use s, not lambda.
  • Results change between runs of cv.glmnet. Fold assignment is random; supply foldid (see above) or set the random seed before the call.

Free alternatives

Tool Language What the documentation says
glmnet MATLAB port MATLAB Maintained by Junyang Qian; per the glmnet vignette a few versions behind the R package
glmnet Python port Python Maintained by B. Balakumar; per the glmnet vignette a few versions behind the R package
scikit-learn ElasticNetCV Python Elastic net fitted along a regularization path with cross-validation; l1_ratio (0 is an L2 penalty, 1 is an L1 penalty) can be a list tested by cross-validation, and alphas defaults to 100 values

Note the naming difference: scikit-learn’s l1_ratio is the L1/L2 mix, the role glmnet’s alpha plays.

FAQ

What is glmnet?

An R package from Friedman, Hastie, Tibshirani and colleagues that fits lasso and elastic-net regularized generalized linear models along a full path of penalty values, with a cross-validation function to select the penalty.

Is glmnet R-only?

The reference implementation is R. MATLAB and Python versions exist but are described by the vignette as a few versions behind.

Which lambda should I report, lambda.min or lambda.1se?

Either is defensible if you say which. lambda.min has the lowest mean cross-validated error; lambda.1se gives the sparsest model within one standard error of it. glmnet’s default when s is omitted is lambda.1se.

How do I cite glmnet?

The CRAN page cites the DOI 10.32614/CRAN.package.glmnet and the Journal of Statistical Software papers: Friedman, Hastie and Tibshirani (2010), J Stat Softw 33(1), 1-22, and the GLM-family and Cox-model papers linked from CRAN (doi:10.18637/jss.v106.i01).

Sources (official docs)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about glmnet in R: Install, Fit and Cross-Validate Lasso

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →