GLMnet: Formula interface for glmnet

View source: R/GLMnet.R

GLMnetR Documentation

Formula interface for glmnet

Description

Fit glmnet models via a formula and a data set for use with predictRisk.

Usage

GLMnet(
  formula,
  data,
  lambda = NULL,
  alpha = 1,
  cv = TRUE,
  nfolds = 10,
  type.measure = "deviance",
  selector = "min",
  family,
  ...
)

Arguments

formula

Formula where the left hand side specifies either a single variable (continuous, binary or categorical), or as a survival outcome (time, event), and the right hand side specifies the linear predictor. Survival outcome can either be specified via Surv or via Hist. Variables on the right hand side of the formula can be marked as unpenalized, see examples. #' For survival outcome, a penalized Cox regression model is fitted. For this the formula may specify variables for which the baseline hazard function should be stratified, see examples.

data

The data used to fit the model.

lambda

A hyperparameter passed to glmnet. If set to NULL, then lambda is chosen by cross-validation, via the function cv.glmnet

alpha

The elasticnet mixing parameter, with 0<=alpha<= 1. alpha =1 is the lasso penalty, and alpha=0 the ridge penalty.

cv

Whether to use cross-validation or not. Default is TRUE.

nfolds

Passed on to cv.glmnet. Number of folds for cross-validation. The default is 10.

type.measure

Passed on to cv.glmnet. Loss to use for cross-validation. Default is deviance.

selector

On of 'min', '1se', 'undersmooth' where the first two are described in the help page of cv.glmnet and the latter is the smallest lambda value where the model could fit. Default is 'min'. When 'undersmooth' is specified no cross-validation is performed.

family

Passed on to glmnet and cv.glmnet. For binary outcome the default is "binomial" and for survival "cox".

...

Additional arguments that are passed on to glmnet and cv.glmnet.

Value

A glmnet object enhanced with the call, the terms to create the design matrix, and in the survival case with the Breslow estimate of the baseline hazard function.

See Also

glmnet

Examples

library(survival)
set.seed(8)
d <- sampleData(87,outcome="survival")
test <- sampleData(5,outcome="survival")

# penalized logistic regression
g <- GLMnet(X2~X1+X8,data=d)
predictRisk(g,newdata=test)
## Not run: 
g1 <- GLMnet(X2~X1+X8,data=d,lambda=0,gamma=0.5)
g2 <- GLMnet(X2~X1+X8,data=d,relax=TRUE)

## End(Not run)
# penalized Cox regression

f0 <- GLMnet(Surv(time,event)~X1+X2+X8+X9,data=d,lambda=0)
predictRisk(f0,newdata=test,times=3)
f <- GLMnet(Surv(time,event)~X1+X2+X8+X9,data=d)
f
predictCox(f,newdata=test,times=5,product.limit=TRUE)
predictRisk(f,newdata=test,times=1)

f1 <- GLMnet(Surv(time,event)~X1+X2+unpenalized(X8)+X9,data=d)

predictRisk(f1,newdata=test,times=1)

riskRegression documentation built on June 8, 2025, 11:33 a.m.