R/tramnet_formula.R

Defines functions .tramnet_update .tramnet_refit .tramnet_baseline .tramnet_formula_fit .tramnet_formula .tramnet_allvars .tramnet_frame Survregnet Lehmannnet BoxCoxnet Lmnet Colrnet Coxphnet tramnet.formula

Documented in BoxCoxnet Colrnet Coxphnet Lehmannnet Lmnet Survregnet tramnet.formula

#' @rdname tramnet
#' @method tramnet formula
#' @export
tramnet.formula <- function(model, data, subset, weights, offset,
                            na.action = na.omit, lambda, alpha,
                            constraints = NULL, ...) {
  call <- match.call()
  call[[1L]] <- as.name("tramnet")
  mf <- .tramnet_frame(call,
    formula = model, data = data,
    env = parent.frame()
  )
  .tramnet_formula(model,
    mf = mf, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = "tram", call = call, ...
  )
}

#' Regularised Transformation Models via Formulae
#'
#' Penalized versions of the transformation models implemented in package
#' tram, specified via a formula. These are convenience wrappers around
#' \code{\link{tramnet}}, analogous to the corresponding functions
#' \code{\link[tram]{Coxph}}, \code{\link[tram]{Colr}},
#' \code{\link[tram]{Lm}}, \code{\link[tram]{BoxCox}},
#' \code{\link[tram]{Lehmann}} and \code{\link[tram]{Survreg}}.
#'
#' The left-hand side of \code{formula} (including strata, as in
#' \code{y | s ~ x}) defines the unpenalized baseline transformation, all
#' terms on the right-hand side are penalized. The design matrix is obtained
#' via \code{\link{model.matrix}} without intercept and its columns are scaled
#' to unit variance. The scaling of the training data is stored and re-used
#' whenever \code{newdata} is supplied to one of the methods, or in
#' \code{\link{cvl_tramnet}}. Coefficients are reported on the original scale
#' of the covariates, see \code{\link{coef.tramnet}}.
#'
#' Not all combinations of error distribution and censoring type lead to
#' objective functions that can be solved by \pkg{CVXR}; see the table in
#' the \code{tramnet} vignette.
#'
#' @param formula an object of class \code{"formula"}, see
#'   \code{\link[tram]{tram}}
#' @param data an optional data frame containing the variables in the model
#' @param subset an optional vector specifying a subset of observations to be
#'   used in the fitting process
#' @param weights an optional vector of case weights to be used in the fitting
#'   process
#' @param offset an optional vector of offsets
#' @param na.action a function which indicates what should happen when the
#'   data contain \code{NA}s
#' @param lambda a positive penalty parameter for the whole penalty function
#' @param alpha a mixing parameter (between zero and one) defining the fraction
#'   between absolute and quadratic penalty terms
#' @param constraints an optional list containing a matrix of linear inequality
#'   contraints on the regression coefficients (on the original scale of the
#'   covariates) and a vector specifying the rhs of the inequality
#' @param \dots additional arguments to the corresponding function in package
#'   tram, e.g., \code{order}, \code{log_first} or \code{support}
#'
#' @return An object of class \code{"tramnet"}, see \code{\link{tramnet}}
#'
#' @author Lucas Kook
#'
#' @keywords model
#'
#' @examples
#' \donttest{
#' if (require("survival") & require("TH.data")) {
#'   data("GBSG2", package = "TH.data")
#'   GBSG2$surv <- with(GBSG2, Surv(time, cens))
#'   fit <- Coxphnet(surv ~ horTh + age + tsize + pnodes,
#'     data = GBSG2,
#'     lambda = 5, alpha = 1, log_first = TRUE
#'   )
#'   coef(fit)
#'   coef(fit, scaled = TRUE)
#'   predict(fit, newdata = GBSG2[1:5, ], type = "survivor", q = 1000)
#' }
#' data("cars")
#' fit <- Lmnet(dist ~ speed, data = cars, lambda = 1, alpha = 0)
#' coef(fit, as.lm = TRUE)
#' }
#' @export
Coxphnet <- function(formula, data, subset, weights, offset,
                     na.action = na.omit, lambda, alpha,
                     constraints = NULL, ...) {
  call <- match.call()
  mf <- .tramnet_frame(call,
    formula = formula, data = data,
    env = parent.frame()
  )
  .tramnet_formula(formula,
    mf = mf, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = "Coxph", call = call, ...
  )
}

#' @rdname Coxphnet
#' @export
Colrnet <- function(formula, data, subset, weights, offset,
                    na.action = na.omit, lambda, alpha,
                    constraints = NULL, ...) {
  call <- match.call()
  mf <- .tramnet_frame(call,
    formula = formula, data = data,
    env = parent.frame()
  )
  .tramnet_formula(formula,
    mf = mf, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = "Colr", call = call, ...
  )
}

#' @rdname Coxphnet
#' @export
Lmnet <- function(formula, data, subset, weights, offset,
                  na.action = na.omit, lambda, alpha,
                  constraints = NULL, ...) {
  call <- match.call()
  mf <- .tramnet_frame(call,
    formula = formula, data = data,
    env = parent.frame()
  )
  .tramnet_formula(formula,
    mf = mf, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = "Lm", call = call, ...
  )
}

#' @rdname Coxphnet
#' @export
BoxCoxnet <- function(formula, data, subset, weights, offset,
                      na.action = na.omit, lambda, alpha,
                      constraints = NULL, ...) {
  call <- match.call()
  mf <- .tramnet_frame(call,
    formula = formula, data = data,
    env = parent.frame()
  )
  .tramnet_formula(formula,
    mf = mf, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = "BoxCox", call = call,
    ...
  )
}

#' @rdname Coxphnet
#' @export
Lehmannnet <- function(formula, data, subset, weights, offset,
                       na.action = na.omit, lambda, alpha,
                       constraints = NULL, ...) {
  call <- match.call()
  mf <- .tramnet_frame(call,
    formula = formula, data = data,
    env = parent.frame()
  )
  .tramnet_formula(formula,
    mf = mf, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = "Lehmann", call = call,
    ...
  )
}

#' @rdname Coxphnet
#' @export
Survregnet <- function(formula, data, subset, weights, offset,
                       na.action = na.omit, lambda, alpha,
                       constraints = NULL, ...) {
  call <- match.call()
  mf <- .tramnet_frame(call,
    formula = formula, data = data,
    env = parent.frame()
  )
  .tramnet_formula(formula,
    mf = mf, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = "Survreg", call = call,
    ...
  )
}

# Helper functions

.tramnet_frame <- function(call, formula, data, env) {
  if (missing(data)) {
    data <- NULL
  }
  mf <- call
  names(mf)[names(mf) == "model"] <- "formula"
  m <- match(c(
    "formula", "data", "subset", "weights", "offset",
    "na.action"
  ), names(mf), 0L)
  mf <- mf[c(1L, m)]
  mf$formula <- .tramnet_allvars(formula, data)
  mf$drop.unused.levels <- TRUE
  mf[[1L]] <- quote(stats::model.frame)
  return(eval(mf, env))
}

.tramnet_allvars <- function(formula, data) {
  tt <- terms(formula, data = data)
  vars <- unique(c(
    all.vars(formula[[2L]]),
    all.vars(delete.response(tt))
  ))
  rhs <- Reduce(function(a, b) call("+", a, b), lapply(vars, as.name))
  ret <- as.formula(call("~", rhs))
  environment(ret) <- environment(formula)
  return(ret)
}

.tramnet_formula <- function(formula, mf, lambda, alpha, constraints, tram,
                             call, ...) {
  weights <- model.weights(mf)
  offset <- model.offset(mf)
  data <- mf[, !(names(mf) %in% c("(weights)", "(offset)")), drop = FALSE]
  attr(data, "terms") <- NULL
  attr(data, "na.action") <- NULL
  .tramnet_formula_fit(formula,
    data = data, weights = weights,
    offset = offset, lambda = lambda, alpha = alpha,
    constraints = constraints, tram = tram,
    tram_args = list(...), call = call
  )
}

.tramnet_formula_fit <- function(formula, data, weights, offset, lambda,
                                 alpha, constraints, tram, tram_args, call) {
  if (!(lambda >= 0 && alpha >= 0 && alpha <= 1)) {
    stop("lambda >= 0 and 0 <= alpha <= 1 is required")
  }
  if (length(formula) < 3L) {
    stop("formula needs a response")
  }
  if ("|" %in% all.names(formula[[3L]])) {
    stop("Scale terms (y ~ x | z) are not supported by tramnet")
  }
  ### baseline model, response and strata only
  bformula <- formula
  bformula[[3L]] <- 1
  model <- .tramnet_baseline(bformula,
    data = data, weights = weights,
    offset = offset, tram = tram,
    tram_args = tram_args
  )
  ### design matrix without intercept, scaled to unit variance
  tt <- delete.response(terms(formula, data = data))
  attr(tt, "intercept") <- 1L
  xmf <- model.frame(tt, data = data, na.action = na.pass)
  X <- model.matrix(tt, data = xmf)
  contrasts <- attr(X, "contrasts")
  X <- X[, colnames(X) != "(Intercept)", drop = FALSE]
  if (ncol(X) == 0L) {
    stop("formula needs at least one covariate on the right-hand side")
  }
  scl <- apply(X, 2, stats::sd)
  scl[!is.finite(scl) | scl < .Machine$double.eps] <- 1
  x <- sweep(X, 2, scl, "/")
  attr(x, "assign") <- attr(x, "contrasts") <- NULL
  if (!is.null(constraints)) {
    constraints[[1]] <- sweep(as.matrix(constraints[[1]]), 2, scl, "/")
  }
  ret <- .tramnet_fit(
    model = model, x = x, lambda = lambda, alpha = alpha,
    constraints = constraints, call = call
  )
  ret$formula <- formula
  ret$terms <- tt
  ret$xlevels <- .getXlevels(tt, xmf)
  ret$contrasts <- contrasts
  ret$scaling <- scl
  ret$data <- data
  ret$weights <- weights
  ret$offset <- offset
  ret$baseline <- list(tram = tram, args = tram_args)
  ret$constraints <- constraints
  if (!is.null(constraints)) {
    ret$constraints[[1]] <- sweep(ret$constraints[[1]], 2, scl, "*")
  }
  return(ret)
}

.tramnet_baseline <- function(formula, data, weights, offset, tram,
                              tram_args) {
  ### evaluate in a child of the formula's environment, such that the
  ### baseline call stays small and functions used in the formula are found
  env <- new.env(parent = environment(formula))
  assign(".tramnet_data", data, envir = env)
  assign(".tramnet_weights", weights, envir = env)
  assign(".tramnet_offset", offset, envir = env)
  environment(formula) <- env
  args <- c(list(formula = formula, data = quote(.tramnet_data)), tram_args)
  if (!is.null(weights)) {
    args$weights <- quote(.tramnet_weights)
  }
  if (!is.null(offset)) {
    args$offset <- quote(.tramnet_offset)
  }
  fun <- call("::", as.name("tram"), as.name(tram))
  return(eval(as.call(c(list(fun), args)), env))
}

.tramnet_refit <- function(object, idx = NULL, lambda, alpha) {
  data <- object$data
  weights <- object$weights
  offset <- object$offset
  if (!is.null(idx)) {
    data <- data[idx, , drop = FALSE]
    weights <- weights[idx]
    offset <- offset[idx]
  }
  call <- object$call
  call$lambda <- lambda
  call$alpha <- alpha
  .tramnet_formula_fit(object$formula,
    data = data, weights = weights,
    offset = offset, lambda = lambda, alpha = alpha,
    constraints = object$constraints,
    tram = object$baseline$tram,
    tram_args = object$baseline$args, call = call
  )
}

.tramnet_update <- function(object, lambda = object$tuning_parm[["lambda"]],
                            alpha = object$tuning_parm[["alpha"]]) {
  if (!is.null(object$scaling)) {
    return(.tramnet_refit(object, lambda = lambda, alpha = alpha))
  }
  ### default interface: refit directly instead of re-evaluating the call,
  ### whose arguments may not be visible from here
  call <- object$call
  call$lambda <- lambda
  call$alpha <- alpha
  do.call(.tramnet_fit, c(list(
    model = object$model, x = object$x,
    lambda = lambda, alpha = alpha,
    constraints = object$constraints,
    call = call
  ), object$solver_args),
  quote = TRUE
  )
}

Try the tramnet package in your browser

Any scripts or data that you put into this service are public.

tramnet documentation built on Oct. 16, 2026, 5:07 p.m.