diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4ebf43f..ed8e074 100755 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -13,7 +13,7 @@ repos: - checkmate - emmeans - formatters - - geeasy + - Matrix - geepack - nlme - rtables diff --git a/DESCRIPTION b/DESCRIPTION index 15b5b75..37a7fb6 100755 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -9,7 +9,17 @@ Authors@R: c( person("Joe", "Zhu", , "joe.zhu@roche.com", role = c("aut", "cre"), comment = c(ORCID = "0000-0001-7566-2787")), person("Emily", "de la Rua", , "emily.de_la_rua@contractors.roche.com", role = "aut"), - person("F. Hoffmann-La Roche AG", role = c("cph", "fnd")) + person("F. Hoffmann-La Roche AG", role = c("cph", "fnd")), + person("Anne Helby", "Petersen", role = c("ctb", "cph"), + comment = "Author of the 'geeasy' code adapted in R/geelm.R"), + person("Lee", "McDaniel", role = c("ctb", "cph"), + comment = "Author of the 'geeM' code adapted in R/geelm.R"), + person("Nick", "Henderson", role = c("ctb", "cph"), + comment = "Author of the 'geeM' code adapted in R/geelm.R"), + person("Melanie", "Prague", role = "ctb", + comment = "Contributed weighting code to 'geeM'"), + person("Søren", "Højsgaard", role = c("ctb", "cph"), + comment = "Author of the 'geeasy' code adapted in R/geelm.R") ) Description: Generalized estimating equations (GEE) are a popular choice for analyzing longitudinal binary outcomes. This package provides an @@ -18,8 +28,10 @@ Description: Generalized estimating equations (GEE) are a popular choice Sabanés Bové et al., 2023) and tabulate results easily using 'rtables' (Becker, Waddell et al., 2023). It builds on 'geepack' (Højsgaard, - Halekoh and Yan, 2006) for the actual GEE model fitting. -License: Apache License 2.0 + Halekoh and Yan, 2006) and adapts the GEE fitting engine of 'geeasy' + (Petersen, McDaniel and + Højsgaard). +License: GPL-3 URL: https://insightsengineering.github.io/tern.gee/, https://github.com/insightsengineering/tern.gee/ BugReports: https://github.com/insightsengineering/tern.gee/issues @@ -30,8 +42,9 @@ Imports: checkmate (>= 2.1.0), emmeans (>= 1.10.4), formatters (>= 0.5.12), - geeasy, geepack, + Matrix, + methods, nlme, rtables (>= 0.6.17), stats @@ -47,11 +60,11 @@ VignetteBuilder: knitr, rmarkdown Config/Needs/verdepcheck: insightsengineering/tern, mllg/checkmate, - rvlenth/emmeans, insightsengineering/formatters, annennenne/geeasy, - cran/geepack, cran/nlme, insightsengineering/rtables, tidyverse/dplyr, + rvlenth/emmeans, insightsengineering/formatters, cran/geepack, + cran/Matrix, cran/nlme, insightsengineering/rtables, tidyverse/dplyr, yihui/knitr, rstudio/rmarkdown, r-lib/testthat, r-lib/vdiffr, r-lib/withr -Config/roxygen2/version: 8.1.0 +Config/roxygen2/version: 8.1.1 Config/testthat/edition: 3 Encoding: UTF-8 Language: en-US diff --git a/NAMESPACE b/NAMESPACE index 01df84a..662908c 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -11,13 +11,18 @@ export(lsmeans) export(s_lsmeans_logistic) export(summarize_gee_logistic) export(vars_gee) +import(Matrix) import(checkmate) import(rtables) importFrom(emmeans,emmeans) importFrom(geepack,QIC) importFrom(nlme,VarCorr) importFrom(rtables,add_colcounts) -importFrom(stats,acf) -importFrom(stats,as.formula) -importFrom(tern,as.rtable) -importFrom(tern,f_conf_level) +importFrom(stats, + acf, + as.formula +) +importFrom(tern, + as.rtable, + f_conf_level +) diff --git a/NEWS.md b/NEWS.md index 29485f3..146cd93 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,10 @@ # tern.gee 0.1.6.9000 +* Removed the dependency on `geeasy`. The GEE fitting engine needed by `fit_gee()` (adapted from + `geeasy` and `geeM`) is now part of `tern.gee`, with `Matrix` as a new dependency. +* Changed the package license to GPL-3, as required by the adapted `geeasy` / `geeM` code. +* Fixed `summary()` failing on `fit_gee()` results when the data contain missing values + (an issue inherited from `geeasy`). # Up version `rtables` package version to 0.6.17. # tern.gee 0.1.5 diff --git a/R/fit_gee.R b/R/fit_gee.R index f925dce..cedd1e4 100644 --- a/R/fit_gee.R +++ b/R/fit_gee.R @@ -62,7 +62,7 @@ build_family <- function(regression) { list( object = result_object, class = result_class, - control = geeasy::geelm.control(scale.fix = TRUE) + control = geelm_control(scale.fix = TRUE) ) } @@ -154,7 +154,7 @@ fit_gee <- function(vars = vars_gee(), cor_struct <- match.arg(cor_struct) cor_details <- build_cor_details(cor_struct, vars, data) - fit <- geeasy::geelm( + fit <- geelm( formula = formula, id = .id, waves = .waves, diff --git a/R/geelm.R b/R/geelm.R new file mode 100644 index 0000000..3db9425 --- /dev/null +++ b/R/geelm.R @@ -0,0 +1,774 @@ +# GEE fitting engine. +# +# The code in this file is adapted from the 'geeasy' package (version 0.1.3, +# , GPL-3) by Anne Helby Petersen, +# Lee McDaniel and Søren Højsgaard, which in turn builds on the 'geeM' package +# (GPL-3) by Lee McDaniel and Nick Henderson. Only the parts needed by +# `fit_gee()` were retained: the "geeasy" engine with "geelm" output, and the +# "exchangeable", "ar1", "m-dependent" and "unstructured" correlation +# structures (plus "independence", which `geepack::QIC()` uses to refit the +# model). Variable names follow the upstream code to ease comparison. +# +# nolint start + +#' Control Settings for GEE Estimation +#' +#' Settings for controlling technical details of the GEE fitting in [geelm()]. +#' +#' @param init.beta (`numeric` or `NULL`)\cr initial values for the mean +#' structure parameters. If `NULL`, these are obtained from a GLM fit. +#' @param init.phi (`number`)\cr initial value of the dispersion parameter. +#' @param tol (`number`)\cr tolerance for asserting convergence. +#' @param maxit (`count`)\cr maximum number of iterations. +#' @param scale.fix (`flag`)\cr whether the dispersion parameter should be fixed +#' at `init.phi`. +#' @param useP (`flag`)\cr whether to use the n-p correction for the dispersion +#' and correlation estimates. +#' @param std.err (`string`)\cr standard error estimation method, either +#' `"san.se"` (sandwich) or `"naive"`. +#' +#' @return A list of values used for controlling model fitting. +#' @keywords internal +geelm_control <- function(init.beta = NULL, init.phi = 1, + tol = 0.00001, maxit = 20, scale.fix = FALSE, + useP = TRUE, std.err = "san.se") { + if (scale.fix && is.null(init.phi)) { + stop("If scale.fix = TRUE, then init.phi must be supplied") + } + list( + init.beta = init.beta, + init.phi = init.phi, + tol = tol, + maxit = maxit, + scale.fix = scale.fix, + useP = as.numeric(useP), + jack = 0, # for geese methods + j1s = 0, # for geese methods + fij = 0, # for geese methods + std.err = std.err + ) +} + +#' Fit a GEE Model with the `geelm` Engine +#' +#' Estimates mean structure parameters and their sandwich standard errors for +#' generalized linear models with correlated observations. The returned object +#' has class `geelm` and is compatible with the `geeglm` methods from `geepack` +#' (e.g. `summary()`, `QIC()`) as well as with `emmeans`. +#' +#' @param formula (`formula`)\cr model formula, possibly including an offset. +#' @param id (`name`)\cr variable in `data` identifying the clusters. +#' @param waves (`name`)\cr numeric variable in `data` giving the time ordering +#' within clusters. Only the ordering is used. +#' @param data (`data.frame`)\cr input data. +#' @param family (`family`)\cr error distribution and link function. +#' @param corstr (`string`)\cr correlation structure, one of `"independence"`, +#' `"exchangeable"`, `"ar1"`, `"m-dependent"` or `"unstructured"`. +#' @param Mv (`count`)\cr order of the `"m-dependent"` structure. +#' @param control (`list`)\cr see [geelm_control()]. +#' +#' @return Object of class `geelm` (inheriting from `geeglm`, `gee`, `glm`, `lm`). +#' @keywords internal +geelm <- function(formula, id, waves, data, + family, corstr = "exchangeable", Mv = 1, + control = geelm_control()) { + thiscall <- match.call() + + corstr <- match.arg(corstr, c("independence", "exchangeable", "ar1", "m-dependent", "unstructured")) + if (corstr == "m-dependent") { + if (!is.numeric(Mv) || !(length(Mv) == 1) || round(Mv, 0) != Mv || Mv < 0) { + stop("Mv must be an integer") + } + attr(corstr, "Mv") <- Mv + } + + if (!inherits(family, "family")) { + stop("family must be a family object") + } + famret <- family + + # Data and variables. + dat <- stats::model.frame(formula, data, na.action = stats::na.pass) + nn <- dim(dat)[1] + + dat$id <- lookup_var_arg(thiscall$id, data, "id") + dat$weights <- rep(1, nn) + dat$waves <- lookup_var_arg(thiscall$waves, data, "waves") + if (!is.numeric(dat$waves)) stop("waves must be numeric") + + formulaoffset <- stats::model.offset(dat) + if (is.null(formulaoffset)) formulaoffset <- rep(0, nn) + dat$offset <- formulaoffset + + # Sort data by id and waves. + neworder <- order(dat$id, dat$waves) + dat <- dat[neworder, ] + + # Only the ordering of the waves is used. + waves_are_equidist <- by(dat$waves, as.factor(dat$id), is_equidistant) + if (any(!waves_are_equidist)) { + warning(paste( + "Non-equidistant waves were provided.", + "Note that only their ordering was used for model fitting.", + "Their numeric values were ignored." + )) + } + dat$waves <- NULL + + # Missing values. + dropind <- which(!stats::complete.cases(dat)) + dat <- stats::na.omit(dat) + + X <- stats::model.matrix(formula, dat) + Y <- stats::model.response(dat) + + results <- geelm_fit( + x = X, y = Y, offset = dat$offset, weights = dat$weights, + control = control, id = dat$id, family = famret, + corstr = corstr + ) + + # Pack output into a geeglm-compatible object. + coefs <- results$beta + names(coefs) <- colnames(X) + + model_rank <- Matrix::rankMatrix(stats::na.omit(X)) + + modelInfo <- list( + mean.link = famret$link, + variance = famret$family, + sca.link = "identity", + cor.link = "identity", + corstr = corstr, + scale.fix = control$scale.fix + ) + + # Alternative variance estimates are not supported: zero placeholders as in geepack. + vbeta <- results$vbeta + vbeta_otherse <- vbeta + vbeta_otherse[, ] <- 0 + vgamma_otherse <- matrix(0, nrow = length(results$phi), ncol = length(results$phi)) + valpha_otherse <- matrix(0, nrow = length(results$alpha), ncol = length(results$alpha)) + + geeseobj <- list( + beta = coefs, + vbeta = vbeta, + vbeta.j1s = vbeta_otherse, + vbeta.fij = vbeta_otherse, + vbeta.ajs = vbeta_otherse, + vbeta.naiv = as.matrix(results$naiv.var), + gamma = results$phi, + vgamma = vgamma_otherse, + vgamma.j1s = vgamma_otherse, + vgamma.fij = vgamma_otherse, + vgamma.ajs = vgamma_otherse, + alpha = results$alpha, + valpha = valpha_otherse, + valpha.j1s = valpha_otherse, + valpha.fij = valpha_otherse, + valpha.ajs = valpha_otherse, + model = modelInfo, + control = control, + error = NA, + clusz = results$clusz, + zsca.names = NULL, + zcor.names = NULL, + xnames = colnames(X) + ) + class(geeseobj) <- c("geese", "list") + + # Restore the input order, leaving out dropped observations. + if (length(dropind) > 0) { + oldorder_noNA <- order(neworder[-dropind]) + } else { + oldorder_noNA <- order(neworder) + } + + out <- list( + coefficients = coefs, + residuals = results$resid[oldorder_noNA], + fitted.values = results$fitted.values[oldorder_noNA], + rank = model_rank, + qr = qr(X), + family = famret, + linear.predictors = results$eta[oldorder_noNA], + weights = results$weights[oldorder_noNA], + prior.weights = dat$weights[oldorder_noNA], + df.residual = sum(results$weights != 0) - model_rank, + y = Y[oldorder_noNA], + model = dat[oldorder_noNA, ], + call = thiscall, + formula = formula, + terms = stats::terms(formula), + data = data, + offset = results$offset[oldorder_noNA], + control = control, + method = "geelm_fit", + constrasts = attr(X, "contrasts"), + xlevels = get_xlevels(dat), + geese = geeseobj, + modelInfo = modelInfo, + id = dat$id[oldorder_noNA], + corstr = corstr, + cor.link = "identity", + std.err = control$std.err + ) + class(out) <- c("geelm", "geeglm", "gee", "glm", "lm") + out +} + +#' Fisher Scoring Algorithm for GEE Models +#' +#' @param x (`matrix`)\cr design matrix, sorted by cluster and time. +#' @param y (`numeric`)\cr response. +#' @param id (`vector`)\cr cluster identifiers. +#' @param offset (`numeric`)\cr offset. +#' @param family (`family`)\cr family object. +#' @param weights (`numeric`)\cr observation weights. +#' @param control (`list`)\cr see [geelm_control()]. +#' @param corstr (`string`)\cr correlation structure, see [geelm()]. +#' +#' @return A list with the estimation results. +#' @keywords internal +geelm_fit <- function(x, y, id, offset, family, weights, control, corstr) { + LinkFun <- family$linkfun + InvLink <- family$linkinv + VarFun <- family$variance + InvLinkDeriv <- family$mu.eta + + p <- ncol(x) + nn <- nrow(x) + + # Basic check that link and variance functions make sense. + meanY <- mean(y) + linkOfMean <- LinkFun(meanY) - mean(offset) + if (!is.finite(linkOfMean)) { + stop(paste( + "Infinite or NaN in the link of the mean of responses.", + "Make sure link function makes sense for these data." + )) + } + if (!is.finite(VarFun(meanY))) { + stop(paste( + "Infinite or NaN in the variance of the mean of responses.", + "Make sure variance function makes sense for these data." + )) + } + + sandwich <- control$std.err == "san.se" + allobs <- TRUE + + # Initialization. + beta <- control$init.beta + if (is.null(beta)) { + m_glm <- stats::glm.fit(x = x, y = y, offset = offset, family = family, weights = weights) + beta <- m_glm$coefficients + } + phi <- control$init.phi + maxit <- control$maxit + scale.fix <- control$scale.fix + useP <- control$useP + tol <- control$tol + + uniqueid <- unique(id) + K <- length(uniqueid) + + includedvec <- weights > 0 + includedlen <- as.numeric(summary(split(y, ifelse(!includedvec, NA, id), drop = TRUE))[, 1]) + len <- as.numeric(summary(split(y, id, drop = TRUE))[, 1]) + + W <- Diagonal(x = weights) + sqrtW <- sqrt(W) + included <- Diagonal(x = as.numeric(includedvec)) + + StdErr <- Diagonal(nn) + dInvLinkdEta <- Diagonal(nn) + Resid <- Diagonal(nn) + + # Initialization according to the correlation structure. + if (corstr == "independence") { + R.alpha.inv <- Diagonal(x = rep.int(1, nn)) / phi + BlockDiag <- get_block_diag(len)$BDiag + } else if (corstr == "ar1") { + tmp <- build_alpha_inv_ar(len) + a1 <- tmp$a1 + a2 <- tmp$a2 + a3 <- tmp$a3 + a4 <- tmp$a4 + row.vec <- tmp$row.vec + col.vec <- tmp$col.vec + BlockDiag <- get_block_diag(len)$BDiag + } else if (corstr == "exchangeable") { + tmp <- get_block_diag(len) + BlockDiag <- tmp$BDiag + n.vec <- vector("numeric", nn) + index <- c(cumsum(len) - len, nn) + for (i in 1:K) { + n.vec[(index[i] + 1):index[i + 1]] <- rep(includedlen[i], len[i]) + } + } else if (corstr == "m-dependent") { + Mv <- attr(corstr, "Mv") + if (Mv >= max(len)) { + stop("Cannot estimate that many parameters: Mv >= max(clustersize)") + } + tmp <- get_block_diag(len) + BlockDiag <- tmp$BDiag + row.vec <- tmp$row.vec + col.vec <- tmp$col.vec + } else if (corstr == "unstructured") { + if (max(len^2 - len) / 2 > length(len)) { + stop("Cannot estimate that many parameters: not enough subjects for unstructured correlation") + } + tmp <- get_block_diag(len) + BlockDiag <- tmp$BDiag + row.vec <- tmp$row.vec + col.vec <- tmp$col.vec + } else { + stop("Unsupported correlation structure") + } + + # Fisher scoring loop. + done <- FALSE + converged <- FALSE + count <- 1 + beta.old <- beta + unstable <- FALSE + + while (!done && count <= maxit) { + eta <- as.vector(x %*% beta) + offset + mu <- InvLink(eta) + diag(StdErr) <- sqrt(1 / VarFun(mu)) + + if (!scale.fix) { + phi <- update_phi(y, mu, VarFun, p, StdErr, included, includedlen, sqrtW, useP) + } + + Resid <- residuals_geelm(StdErr = StdErr, included = included, sqrtW = sqrtW, YY = y, mu = mu) + + if (corstr == "ar1") { + alpha.new <- update_alpha_ar( + y, mu, VarFun, phi, id, len, StdErr, Resid, p, + included, includedlen, includedvec, allobs, + sqrtW, BlockDiag, useP + ) + R.alpha.inv <- get_alpha_inv_ar(alpha.new, a1, a2, a3, a4, row.vec, col.vec) / phi + } else if (corstr == "exchangeable") { + alpha.new <- update_alpha_ex( + y, mu, VarFun, phi, id, len, StdErr, + Resid, p, BlockDiag, included, + includedlen, sqrtW, useP + ) + R.alpha.inv <- get_alpha_inv_ex(alpha.new, n.vec, BlockDiag) / phi + } else if (corstr == "m-dependent") { + if (Mv == 1) { + alpha.new <- update_alpha_ar( + y, mu, VarFun, phi, id, len, StdErr, Resid, p, + included, includedlen, includedvec, allobs, + sqrtW, BlockDiag, useP + ) + } else { + alpha.new <- update_alpha_mdep( + y, mu, VarFun, phi, id, len, + StdErr, Resid, p, BlockDiag, Mv, + included, includedlen, + allobs, sqrtW, useP + ) + if (sum(len > Mv) <= p) { + unstable <- TRUE + } + } + if (any(alpha.new >= 1)) { + done <- TRUE + warning("An estimated correlation great than 1 was found, stopping before convergence.") + } + R.alpha.inv <- get_alpha_inv_mdep(alpha.new, len, row.vec, col.vec) / phi + } else if (corstr == "unstructured") { + alpha.new <- update_alpha_unstruc( + y, mu, VarFun, phi, id, len, + StdErr, Resid, p, BlockDiag, + included, includedlen, allobs, + sqrtW, useP + ) + if (any(alpha.new >= 1)) { + done <- TRUE + warning("An estimated correlation great than 1 was found, stopping before convergence.") + } + R.alpha.inv <- get_alpha_inv_unstruc(alpha.new, len, row.vec, col.vec) / phi + } else if (corstr == "independence") { + R.alpha.inv <- Diagonal(x = rep.int(1 / phi, nn)) + alpha.new <- "independent" + } + + beta.list <- update_beta( + y, x, beta, offset, InvLinkDeriv, InvLink, VarFun, R.alpha.inv, StdErr, + dInvLinkdEta, tol, W, included + ) + beta <- beta.list$beta + + if (max(abs((beta - beta.old) / (beta.old + .Machine$double.eps))) < tol) { + converged <- TRUE + done <- TRUE + } + beta.old <- beta + count <- count + 1 + } + + biggest <- which.max(len)[1] + index <- sum(len[1:biggest]) - len[biggest] + if (K == 1) { + biggest.R.alpha <- solve(R.alpha.inv) + } else { + biggest.R.alpha.inv <- R.alpha.inv[(index + 1):(index + len[biggest]), (index + 1):(index + len[biggest])] + biggest.R.alpha <- solve(biggest.R.alpha.inv) + } + + eta <- as.vector(x %*% beta) + offset + if (sandwich) { + sandvar.list <- get_sandwich( + y, x, eta, id, R.alpha.inv, phi, InvLinkDeriv, InvLink, VarFun, + beta.list$hess, StdErr, dInvLinkdEta, BlockDiag, W, included + ) + } else { + sandvar.list <- list(sandvar = "no sandwich") + } + + alpha <- alpha.new + if (is.character(alpha)) { + alpha <- 0 + } + + pearson_resid <- (y - mu) * diag(sqrtW) / VarFun(mu) + fitted.values <- InvLink(eta) + + if (!converged) { + warning("Did not converge") + } + if (unstable) { + warning(paste( + "Number of subjects with number of observations >= Mv is very small,", + "some correlations are estimated with very low sample size." + )) + } + + beta <- as.vector(beta) + names(beta) <- colnames(x) + + out <- list( + alpha = alpha, + beta = beta, + phi = phi, + niter = count - 1, + naiv.var = solve(beta.list$hess), + corr = corstr, + clusz = len, + FunList = family, + offset = offset, + eta = eta, + weights = weights, + biggest.R.alpha = biggest.R.alpha / phi, + resid = pearson_resid, + fitted.values = fitted.values, + vbeta = as.matrix(sandvar.list$sandvar) + ) + class(out) <- c("geelm_fit", "list") + out +} + +# Utilities ---- + +# Find variable names or expressions in data or the calling environment of `geelm()`. +lookup_var_arg <- function(arg, data, name = NULL) { + out <- eval(arg, envir = data, enclos = parent.frame(n = 2)) + if (length(out) == 1) { + out <- get(arg, envir = as.environment(data)) + } + if (length(out) != nrow(data)) { + stop(paste("Invalid", ifelse(is.null(name), "argument", name))) + } + out +} + +# Get levels for all factors from a model frame. +get_xlevels <- function(modelframe) { + classes <- attr(stats::terms(modelframe), "dataClasses") + factors <- names(classes[classes == "factor"]) + nfactors <- length(factors) + if (nfactors > 0) { + xlevels <- as.list(1:nfactors) + for (i in 1:nfactors) { + xlevels[[i]] <- levels(modelframe[, factors[i]]) + } + names(xlevels) <- factors + return(xlevels) + } + NULL +} + +# Check whether a sorted numeric vector is equidistant. +is_equidistant <- function(x) { + nx <- length(x) + if (nx > 1) { + length(unique(x[-1] - x[-nx])) == 1 + } else { + TRUE + } +} + +# Pearson-type residual matrix. +residuals_geelm <- function(StdErr, included, sqrtW, YY, mu) { + StdErr %*% included %*% sqrtW %*% Diagonal(x = YY - mu) +} + +# Simple moment estimator of the dispersion parameter. +update_phi <- function(YY, mu, VarFun, p, StdErr, included, includedlen, sqrtW, useP) { + resid <- diag(StdErr %*% included %*% sqrtW %*% Diagonal(x = YY - mu)) + phi <- (1 / (sum(included) - useP * p)) * crossprod(resid, resid) + as.numeric(phi) +} + +# Update the coefficients (10 Newton steps given the current working correlation). +update_beta <- function(YY, XX, beta, offset, InvLinkDeriv, InvLink, + VarFun, R.alpha.inv, StdErr, dInvLinkdEta, tol, W, included) { + beta.new <- beta + for (i in 1:10) { + eta <- as.vector(XX %*% beta.new) + offset + diag(dInvLinkdEta) <- InvLinkDeriv(eta) + mu <- InvLink(eta) + diag(StdErr) <- sqrt(1 / VarFun(mu)) + + hess <- crossprod( + StdErr %*% dInvLinkdEta %*% XX, + R.alpha.inv %*% W %*% StdErr %*% dInvLinkdEta %*% XX + ) + esteq <- crossprod( + StdErr %*% dInvLinkdEta %*% XX, + R.alpha.inv %*% W %*% StdErr %*% as.matrix(YY - mu) + ) + update <- solve(hess, esteq) + beta.new <- beta.new + as.vector(update) + } + list(beta = beta.new, hess = hess) +} + +# Sandwich variance estimator. +get_sandwich <- function(YY, XX, eta, id, R.alpha.inv, phi, InvLinkDeriv, + InvLink, VarFun, hessMat, StdErr, dInvLinkdEta, + BlockDiag, W, included) { + diag(dInvLinkdEta) <- InvLinkDeriv(eta) + mu <- InvLink(eta) + diag(StdErr) <- sqrt(1 / VarFun(mu)) + scoreDiag <- Diagonal(x = YY - mu) + BlockDiag <- scoreDiag %*% BlockDiag %*% scoreDiag + + numsand <- as.matrix(crossprod( + StdErr %*% dInvLinkdEta %*% XX, + R.alpha.inv %*% W %*% StdErr %*% + BlockDiag %*% StdErr %*% W %*% + R.alpha.inv %*% StdErr %*% + dInvLinkdEta %*% XX + )) + + sandvar <- t(solve(hessMat, numsand)) + sandvar <- t(solve(t(hessMat), sandvar)) + list(sandvar = sandvar, numsand = numsand) +} + +# Block diagonal matrix of ones with one block per cluster. +get_block_diag <- function(len) { + K <- length(len) + xvec <- rep.int(1, sum(len^2)) + row.vec <- col.vec <- vector("numeric", sum(len^2)) + add.vec <- cumsum(len) - len + if (K == 1) { + index <- c(0, sum(len^2)) + } else { + index <- c(0, (cumsum(len^2) - len^2)[2:K], sum(len^2)) + } + for (i in 1:K) { + row.vec[(index[i] + 1):(index[i + 1])] <- rep.int((1:len[i]) + add.vec[i], len[i]) + col.vec[(index[i] + 1):(index[i + 1])] <- rep((1:len[i]) + add.vec[i], each = len[i]) + } + BlockDiag <- sparseMatrix(i = row.vec, j = col.vec, x = xvec) + list(BDiag = symmpart(BlockDiag), row.vec = row.vec, col.vec = col.vec) +} + +# Correlation parameter updates ---- + +# Exchangeable correlation. +update_alpha_ex <- function(YY, mu, VarFun, phi, id, len, StdErr, + Resid, p, BlockDiag, included, + includedlen, sqrtW, useP) { + W <- sqrtW^2 + denom <- phi * (sum(includedlen * (includedlen - 1)) / 2 - useP * p) + BlockDiag <- StdErr %*% Diagonal(x = YY - mu) %*% included %*% BlockDiag %*% W %*% + Diagonal(x = YY - mu) %*% StdErr + alpha <- sum(triu(BlockDiag, k = 1)) + alpha / denom +} + +# M-dependent correlation. +update_alpha_mdep <- function(YY, mu, VarFun, phi, id, len, + StdErr, Resid, p, BlockDiag, m, + included, includedlen, allobs, sqrtW, useP) { + BlockDiag <- Resid %*% BlockDiag %*% Resid + alpha.new <- vector("numeric", m) + for (i in 1:m) { + bandmat <- drop0(band(BlockDiag, i, i)) + # If there are few observations for a parameter, don't subtract p to avoid NaN. + use_p_i <- if (sum(includedlen > i) > p) useP else 0 + if (allobs) { + alpha.new[i] <- sum(bandmat) / (phi * (sum(as.numeric(len > i) * (len - i)) - use_p_i * p)) + } else { + alpha.new[i] <- sum(bandmat) / (phi * (length(bandmat@i) - use_p_i * p)) + } + } + alpha.new +} + +# AR-1 correlation, also used for 1-dependent. +update_alpha_ar <- function(YY, mu, VarFun, phi, id, len, StdErr, Resid, p, + included, includedlen, includedvec, allobs, + sqrtW, BlockDiag, useP) { + Resid <- StdErr %*% included %*% sqrtW %*% Diagonal(x = YY - mu) + denom <- phi * (sum(band(triu(included %*% BlockDiag %*% included, k = 1), k1 = 1, k2 = 1)) - useP * p) + num <- sum(band(triu(Resid %*% BlockDiag %*% Resid, k = 1), k1 = 1, k2 = 1)) + as.numeric(num / denom) +} + +# Unstructured correlation. +update_alpha_unstruc <- function(YY, mu, VarFun, phi, id, len, StdErr, Resid, + p, BlockDiag, included, includedlen, + allobs, sqrtW, useP) { + ml <- max(len) + BlockDiag <- Resid %*% BlockDiag %*% Resid + alpha.new <- vector("numeric", sum(1:(ml - 1))) + lalph <- length(alpha.new) + + row.vec <- NULL + col.vec <- NULL + for (i in 2:ml) { + row.vec <- c(row.vec, 1:(i - 1)) + col.vec <- c(col.vec, rep(i, each = i - 1)) + } + index <- cumsum(len) - len + if (sum(includedlen == max(len)) <= p) { + stop("Number of clusters of largest size is less than p.") + } + for (i in 1:lalph) { + newrow <- index[which(len >= col.vec[i])] + row.vec[i] + newcol <- index[which(len >= col.vec[i])] + col.vec[i] + bdtmp <- BlockDiag[cbind(newrow, newcol)] + if (allobs) { + denom <- phi * (length(newrow) - useP * p) + } else { + denom <- phi * (sum(bdtmp != 0) - useP * p) + } + alpha.new[i] <- sum(bdtmp) / denom + } + alpha.new +} + +# Inverse correlation matrices ---- + +# AR-1 inverse. +get_alpha_inv_ar <- function(alpha.new, a1, a2, a3, a4, row.vec, col.vec) { + corr.vec <- c( + alpha.new * a1 / (1 - alpha.new^2), + ((1 + alpha.new^2) * a2 + a3) / (1 - alpha.new^2) + a4, + alpha.new * a1 / (1 - alpha.new^2) + ) + methods::as(sparseMatrix(i = row.vec, j = col.vec, x = corr.vec), "symmetricMatrix") +} + +# Index structures for the AR-1 inverse. +build_alpha_inv_ar <- function(len) { + nn <- sum(len) + K <- length(len) + a1 <- a2 <- a3 <- a4 <- vector("numeric", nn) + index <- c(cumsum(len) - len, nn) + + for (i in 1:K) { + if (len[i] > 1) { + a1[(index[i] + 1):index[i + 1]] <- c(rep(-1, times = len[i] - 1), 0) + a2[(index[i] + 1):index[i + 1]] <- c(0, rep(1, times = len[i] - 2), 0) + a3[(index[i] + 1):index[i + 1]] <- c(1, rep(0, times = len[i] - 2), 1) + a4[(index[i] + 1):index[i + 1]] <- c(rep(0, times = len[i])) + } else if (len[i] == 1) { + a1[(index[i] + 1):index[i + 1]] <- 0 + a2[(index[i] + 1):index[i + 1]] <- 0 + a3[(index[i] + 1):index[i + 1]] <- 0 + a4[(index[i] + 1):index[i + 1]] <- 1 + } + } + + a1 <- a1[1:(nn - 1)] + subdiag.col <- 1:(nn - 1) + subdiag.row <- 2:nn + + row.vec <- c(subdiag.row, (1:nn), subdiag.col) + col.vec <- c(subdiag.col, (1:nn), subdiag.row) + list(row.vec = row.vec, col.vec = col.vec, a1 = a1, a2 = a2, a3 = a3, a4 = a4) +} + +# Exchangeable inverse. +get_alpha_inv_ex <- function(alpha.new, diag.vec, BlockDiag) { + methods::as( + BlockDiag %*% Diagonal(x = (-alpha.new / ((1 - alpha.new) * (1 + (diag.vec - 1) * alpha.new)))) + + Diagonal(x = ((1 + (diag.vec - 2) * alpha.new) / ((1 - alpha.new) * (1 + (diag.vec - 1) * alpha.new)) + + alpha.new / ((1 - alpha.new) * (1 + (diag.vec - 1) * alpha.new)))), + "symmetricMatrix" + ) +} + +# M-dependent inverse. +get_alpha_inv_mdep <- function(alpha.new, len, row.vec, col.vec) { + m <- length(alpha.new) + mat.sizes <- sort(unique(len)) + mat.inverses <- list() + + for (i in seq_along(mat.sizes)) { + if (mat.sizes[i] == 1) { + mat.inverses[[i]] <- 1 + } else { + mtmp <- min(m, mat.sizes[i] - 1) + a1 <- list() + a1[[1]] <- rep(1, mat.sizes[i]) + for (j in 1:mtmp) { + a1[[j + 1]] <- rep(alpha.new[j], mat.sizes[i] - j) + } + tmp <- bandSparse(mat.sizes[i], k = c(0:mtmp), diagonals = a1, symmetric = TRUE) + mat.inverses[[i]] <- as.vector(solve(tmp)) + } + } + mat.finder <- match(len, mat.sizes) + corr.vec <- unlist(mat.inverses[mat.finder]) + methods::as(sparseMatrix(i = row.vec, j = col.vec, x = corr.vec), "symmetricMatrix") +} + +# Unstructured inverse. +get_alpha_inv_unstruc <- function(alpha.new, len, row.vec, col.vec) { + unstr.row <- NULL + unstr.col <- NULL + ml <- max(len) + for (i in 2:ml) { + unstr.row <- c(unstr.row, 1:(i - 1)) + unstr.col <- c(unstr.col, rep(i, each = i - 1)) + } + unstr.row <- c(unstr.row, 1:ml) + unstr.col <- c(unstr.col, 1:ml) + xvec <- c(alpha.new, rep(1, ml)) + # The biggest matrix implied by the cluster sizes. + biggestMat <- forceSymmetric(sparseMatrix(i = unstr.row, j = unstr.col, x = xvec)) + + mat.sizes <- sort(unique(len)) + mat.inverses <- list() + for (i in seq_along(mat.sizes)) { + tmp <- biggestMat[1:mat.sizes[i], 1:mat.sizes[i]] + mat.inverses[[i]] <- as.vector(solve(tmp)) + } + mat.finder <- match(len, mat.sizes) + corr.vec <- unlist(mat.inverses[mat.finder]) + methods::as(sparseMatrix(i = row.vec, j = col.vec, x = corr.vec), "symmetricMatrix") +} + +# nolint end diff --git a/R/package.R b/R/package.R index 567ad33..321e77f 100644 --- a/R/package.R +++ b/R/package.R @@ -10,6 +10,7 @@ #' @importFrom stats acf as.formula #' @importFrom tern f_conf_level #' @importFrom emmeans emmeans +#' @import Matrix NULL # to avoid NOTEs from R CMD CHECK diff --git a/README.md b/README.md index 534555a..575f428 100644 --- a/README.md +++ b/README.md @@ -22,12 +22,12 @@ ## Overview -`tern.gee` provides an interface for generalized estimating equations (GEE) within the [`tern`](https://insightsengineering.github.io/tern/) framework to produce commonly used tables (using [`rtables`](https://pharmaverse.github.io/rtables/) and graphs. +`tern.gee` provides an interface for generalized estimating equations (GEE) within the [`tern`](https://pharmaverse.github.io/tern/) framework to produce commonly used tables (using [`rtables`](https://pharmaverse.github.io/rtables/) and graphs. It builds on the R-package `geepack` for the actual GEE calculations. ## When to use this package -If you would like to use the [`tern`](https://insightsengineering.github.io/tern/) framework for tabulation and graphs, then this package is ideal for your GEE fits. +If you would like to use the [`tern`](https://pharmaverse.github.io/tern/) framework for tabulation and graphs, then this package is ideal for your GEE fits. However if you use another reporting framework then it will be better to directly use `geepack` and perform the tabulation and plots differently. ## Main Features @@ -88,11 +88,4 @@ For more information on how GEE models and their `rtables` tables are created se ## Stargazers -### Current - -[![Stargazers repo roster for @insightsengineering/tern.gee](https://reporoster.com/stars/insightsengineering/tern.gee)](https://github.com/insightsengineering/tern.gee/stargazers) -[![Forkers repo roster for @insightsengineering/tern.gee](https://reporoster.com/forks/insightsengineering/tern.gee)](https://github.com/insightsengineering/tern.gee/network/members) - -### Over time - [![Stargazers over time](https://starchart.cc/insightsengineering/tern.gee.svg)](https://starchart.cc/insightsengineering/tern.gee) diff --git a/inst/WORDLIST b/inst/WORDLIST index 8987c99..b137554 100644 --- a/inst/WORDLIST +++ b/inst/WORDLIST @@ -1,9 +1,9 @@ Bové COPD FEV -Forkers GEEs Halekoh +Helby Hoffmann Højsgaard ORCID @@ -20,6 +20,9 @@ de doi et funder +geeasy +geelm +geeM geepack jss pkgdown diff --git a/man/geelm.Rd b/man/geelm.Rd new file mode 100644 index 0000000..44deb9e --- /dev/null +++ b/man/geelm.Rd @@ -0,0 +1,46 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geelm.R +\name{geelm} +\alias{geelm} +\title{Fit a GEE Model with the \code{geelm} Engine} +\usage{ +geelm( + formula, + id, + waves, + data, + family, + corstr = "exchangeable", + Mv = 1, + control = geelm_control() +) +} +\arguments{ +\item{formula}{(\code{formula})\cr model formula, possibly including an offset.} + +\item{id}{(\code{name})\cr variable in \code{data} identifying the clusters.} + +\item{waves}{(\code{name})\cr numeric variable in \code{data} giving the time ordering +within clusters. Only the ordering is used.} + +\item{data}{(\code{data.frame})\cr input data.} + +\item{family}{(\code{family})\cr error distribution and link function.} + +\item{corstr}{(\code{string})\cr correlation structure, one of \code{"independence"}, +\code{"exchangeable"}, \code{"ar1"}, \code{"m-dependent"} or \code{"unstructured"}.} + +\item{Mv}{(\code{count})\cr order of the \code{"m-dependent"} structure.} + +\item{control}{(\code{list})\cr see \code{\link[=geelm_control]{geelm_control()}}.} +} +\value{ +Object of class \code{geelm} (inheriting from \code{geeglm}, \code{gee}, \code{glm}, \code{lm}). +} +\description{ +Estimates mean structure parameters and their sandwich standard errors for +generalized linear models with correlated observations. The returned object +has class \code{geelm} and is compatible with the \code{geeglm} methods from \code{geepack} +(e.g. \code{summary()}, \code{QIC()}) as well as with \code{emmeans}. +} +\keyword{internal} diff --git a/man/geelm_control.Rd b/man/geelm_control.Rd new file mode 100644 index 0000000..c13a174 --- /dev/null +++ b/man/geelm_control.Rd @@ -0,0 +1,42 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geelm.R +\name{geelm_control} +\alias{geelm_control} +\title{Control Settings for GEE Estimation} +\usage{ +geelm_control( + init.beta = NULL, + init.phi = 1, + tol = 1e-05, + maxit = 20, + scale.fix = FALSE, + useP = TRUE, + std.err = "san.se" +) +} +\arguments{ +\item{init.beta}{(\code{numeric} or \code{NULL})\cr initial values for the mean +structure parameters. If \code{NULL}, these are obtained from a GLM fit.} + +\item{init.phi}{(\code{number})\cr initial value of the dispersion parameter.} + +\item{tol}{(\code{number})\cr tolerance for asserting convergence.} + +\item{maxit}{(\code{count})\cr maximum number of iterations.} + +\item{scale.fix}{(\code{flag})\cr whether the dispersion parameter should be fixed +at \code{init.phi}.} + +\item{useP}{(\code{flag})\cr whether to use the n-p correction for the dispersion +and correlation estimates.} + +\item{std.err}{(\code{string})\cr standard error estimation method, either +\code{"san.se"} (sandwich) or \code{"naive"}.} +} +\value{ +A list of values used for controlling model fitting. +} +\description{ +Settings for controlling technical details of the GEE fitting in \code{\link[=geelm]{geelm()}}. +} +\keyword{internal} diff --git a/man/geelm_fit.Rd b/man/geelm_fit.Rd new file mode 100644 index 0000000..686afe7 --- /dev/null +++ b/man/geelm_fit.Rd @@ -0,0 +1,32 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/geelm.R +\name{geelm_fit} +\alias{geelm_fit} +\title{Fisher Scoring Algorithm for GEE Models} +\usage{ +geelm_fit(x, y, id, offset, family, weights, control, corstr) +} +\arguments{ +\item{x}{(\code{matrix})\cr design matrix, sorted by cluster and time.} + +\item{y}{(\code{numeric})\cr response.} + +\item{id}{(\code{vector})\cr cluster identifiers.} + +\item{offset}{(\code{numeric})\cr offset.} + +\item{family}{(\code{family})\cr family object.} + +\item{weights}{(\code{numeric})\cr observation weights.} + +\item{control}{(\code{list})\cr see \code{\link[=geelm_control]{geelm_control()}}.} + +\item{corstr}{(\code{string})\cr correlation structure, see \code{\link[=geelm]{geelm()}}.} +} +\value{ +A list with the estimation results. +} +\description{ +Fisher Scoring Algorithm for GEE Models +} +\keyword{internal} diff --git a/man/tern.gee-package.Rd b/man/tern.gee-package.Rd index b5ae750..7034d19 100644 --- a/man/tern.gee-package.Rd +++ b/man/tern.gee-package.Rd @@ -30,6 +30,11 @@ Authors: Other contributors: \itemize{ \item F. Hoffmann-La Roche AG [copyright holder, funder] + \item Anne Helby Petersen (Author of the 'geeasy' code adapted in R/geelm.R) [contributor, copyright holder] + \item Lee McDaniel (Author of the 'geeM' code adapted in R/geelm.R) [contributor, copyright holder] + \item Nick Henderson (Author of the 'geeM' code adapted in R/geelm.R) [contributor, copyright holder] + \item Melanie Prague (Contributed weighting code to 'geeM') [contributor] + \item Søren Højsgaard (Author of the 'geeasy' code adapted in R/geelm.R) [contributor, copyright holder] } } diff --git a/tests/testthat/test-fit_gee.R b/tests/testthat/test-fit_gee.R index 41475af..2f6a8af 100644 --- a/tests/testthat/test-fit_gee.R +++ b/tests/testthat/test-fit_gee.R @@ -112,3 +112,11 @@ test_that("fit_gee works as expected for Toeplitz correlation structure", { )) expect_class(result, c("tern_gee_logistic", "tern_gee", "geelm")) }) + +test_that("summary works for fit_gee results with missing responses", { + expect_true(anyNA(fev_data$FEV1_BINARY)) + result <- fit_gee(vars = fev_vars, data = fev_data) + coefs <- withr::with_options(opts_partial_match_old, stats::coef(summary(result))) + expect_data_frame(coefs, nrows = 4L) + expect_equal(coefs$Estimate, unname(stats::coef(result))) +}) diff --git a/tests/testthat/test-geelm.R b/tests/testthat/test-geelm.R new file mode 100644 index 0000000..b6b645a --- /dev/null +++ b/tests/testthat/test-geelm.R @@ -0,0 +1,451 @@ +# Setup ---- + +# Same preparation as in `fit_gee()`. The data contain missing responses. +geelm_data <- local({ + d <- as.data.frame(fev_data) + d$.id <- as.integer(d$USUBJID) + d$.waves <- as.integer(d$AVISIT) + d[order(d$.id, d$.waves), ] +}) +geelm_formula <- FEV1_BINARY ~ ARMCD + RACE +geelm_n_complete <- sum(stats::complete.cases(geelm_data[c("FEV1_BINARY", "ARMCD", "RACE")])) + +# Subjects with complete data at all 4 visits. +geelm_ids_4 <- local({ + n_obs <- tapply(!is.na(geelm_data$FEV1_BINARY), geelm_data$.id, sum) + as.integer(names(n_obs)[n_obs == 4]) +}) + +fit_geelm <- function(corstr, mv = 1, data = geelm_data, control = geelm_control(scale.fix = TRUE), + formula = geelm_formula) { + geelm( + formula, + id = .id, waves = .waves, data = data, family = stats::binomial(), + corstr = corstr, Mv = mv, control = control + ) +} + +# Small toy data: 3 clusters with sizes 2, 3, 3. +toy_len <- c(2, 3, 3) + +# Builds the dense block diagonal matrix with one `block_fun(size)` block per cluster. +dense_block_diag <- function(len, block_fun) { + n <- sum(len) + out <- matrix(0, n, n) + start <- cumsum(len) - len + for (i in seq_along(len)) { + idx <- start[i] + seq_len(len[i]) + out[idx, idx] <- block_fun(len[i]) + } + out +} + +# geelm_control ---- + +test_that("geelm_control returns the expected defaults", { + result <- geelm_control() + expect_list(result) + expect_null(result$init.beta) + expect_identical(result$init.phi, 1) + expect_identical(result$tol, 0.00001) + expect_identical(result$maxit, 20) + expect_false(result$scale.fix) + expect_identical(result$useP, 1) + expect_identical(result$std.err, "san.se") + expect_identical(result[c("jack", "j1s", "fij")], list(jack = 0, j1s = 0, fij = 0)) +}) + +test_that("geelm_control converts useP to numeric", { + expect_identical(geelm_control(useP = FALSE)$useP, 0) +}) + +test_that("geelm_control fails when scale is fixed without initial dispersion", { + expect_error( + geelm_control(scale.fix = TRUE, init.phi = NULL), + "init.phi must be supplied" + ) +}) + +# Utilities ---- + +test_that("is_equidistant works as expected", { + expect_true(is_equidistant(numeric(0))) + expect_true(is_equidistant(5)) + expect_true(is_equidistant(c(1, 2, 3))) + expect_true(is_equidistant(c(2, 4, 6, 8))) + expect_false(is_equidistant(c(1, 2, 7))) +}) + +test_that("get_xlevels returns factor levels from a model frame", { + mf <- stats::model.frame(geelm_formula, geelm_data) + result <- get_xlevels(mf) + expect_identical(names(result), c("ARMCD", "RACE")) + expect_identical(result$ARMCD, levels(geelm_data$ARMCD)) + expect_identical(result$RACE, levels(geelm_data$RACE)) +}) + +test_that("get_xlevels returns NULL when there are no factors", { + mf <- stats::model.frame(FEV1_BINARY ~ FEV1, geelm_data) + expect_null(get_xlevels(mf)) +}) + +test_that("lookup_var_arg finds variables in data by name and by string", { + data <- data.frame(a = 1:3, b = 4:6) + wrapper <- function(arg) lookup_var_arg(substitute(arg), data, "x") + expect_identical(wrapper(a), 1:3) + expect_identical(wrapper("b"), 4:6) +}) + +test_that("lookup_var_arg fails for variables with wrong length", { + data <- data.frame(a = 1:3) + wrong <- 1:2 # nolint + wrapper <- function(arg) lookup_var_arg(substitute(arg), data, "id") + expect_error(wrapper(wrong), "Invalid id") +}) + +test_that("get_block_diag returns block diagonal matrix of ones with indices", { + result <- get_block_diag(toy_len) + expect_identical(names(result), c("BDiag", "row.vec", "col.vec")) + expected <- dense_block_diag(toy_len, function(n) matrix(1, n, n)) + expect_equal(as.matrix(result$BDiag), expected, ignore_attr = TRUE) + expect_length(result$row.vec, sum(toy_len^2)) + expect_length(result$col.vec, sum(toy_len^2)) +}) + +test_that("get_block_diag works with a single cluster", { + result <- get_block_diag(3) + expect_equal(as.matrix(result$BDiag), matrix(1, 3, 3), ignore_attr = TRUE) +}) + +# Inverse correlation matrices ---- + +test_that("get_alpha_inv_ar returns the inverse AR1 correlation matrix", { + alpha <- 0.4 + len <- c(1, toy_len) + tmp <- build_alpha_inv_ar(len) + result <- get_alpha_inv_ar(alpha, tmp$a1, tmp$a2, tmp$a3, tmp$a4, tmp$row.vec, tmp$col.vec) + expected <- dense_block_diag(len, function(n) solve(alpha^abs(outer(seq_len(n), seq_len(n), "-")))) + expect_equal(as.matrix(result), expected, ignore_attr = TRUE, tolerance = 1e-10) +}) + +test_that("get_alpha_inv_ex returns the inverse exchangeable correlation matrix", { + alpha <- 0.3 + block_diag <- get_block_diag(toy_len)$BDiag + n_vec <- rep(toy_len, toy_len) + result <- get_alpha_inv_ex(alpha, n_vec, block_diag) + expected <- dense_block_diag(toy_len, function(n) { + m <- matrix(alpha, n, n) + diag(m) <- 1 + solve(m) + }) + expect_equal(as.matrix(result), expected, ignore_attr = TRUE, tolerance = 1e-10) +}) + +test_that("get_alpha_inv_mdep returns the inverse banded correlation matrix", { + alpha <- c(0.3, 0.1) + len <- c(1, toy_len, 4) + tmp <- get_block_diag(len) + result <- get_alpha_inv_mdep(alpha, len, tmp$row.vec, tmp$col.vec) + expected <- dense_block_diag(len, function(n) { + lag <- abs(outer(seq_len(n), seq_len(n), "-")) + m <- ifelse(lag == 0, 1, ifelse(lag <= length(alpha), alpha[pmax(lag, 1)], 0)) + solve(m) + }) + expect_equal(as.matrix(result), expected, ignore_attr = TRUE, tolerance = 1e-10) +}) + +test_that("get_alpha_inv_unstruc returns the inverse unstructured correlation matrix", { + # Upper triangle in column-major order: (1,2), (1,3), (2,3). + alpha <- c(0.2, 0.1, 0.3) + tmp <- get_block_diag(toy_len) + result <- get_alpha_inv_unstruc(alpha, toy_len, tmp$row.vec, tmp$col.vec) + full <- diag(3) + full[upper.tri(full)] <- alpha + full[lower.tri(full)] <- t(full)[lower.tri(full)] + expected <- dense_block_diag(toy_len, function(n) solve(full[seq_len(n), seq_len(n), drop = FALSE])) + expect_equal(as.matrix(result), expected, ignore_attr = TRUE, tolerance = 1e-10) +}) + +# geelm results ---- + +test_that("geelm returns a geeglm compatible object", { + result <- expect_silent(geelm( + geelm_formula, + id = .id, waves = .waves, data = geelm_data, family = stats::binomial(), + corstr = "exchangeable", control = geelm_control(scale.fix = TRUE) + )) + expect_class(result, c("geelm", "geeglm", "gee", "glm", "lm")) + expect_class(result$geese, "geese") + expect_named(coef(result), c("(Intercept)", "ARMCDTRT", "RACEBlack or African American", "RACEWhite")) + expect_identical(dim(vcov(result)), c(4L, 4L)) + expect_identical(result$corstr, "exchangeable") + expect_identical(result$std.err, "san.se") + expect_length(result$fitted.values, geelm_n_complete) + expect_length(result$id, geelm_n_complete) + expect_identical(result$xlevels$ARMCD, levels(geelm_data$ARMCD)) + # Partial matching happens inside the `geepack` methods. + withr::with_options(opts_partial_match_old, { + expect_data_frame(stats::coef(summary(result)), nrows = 4L) + }) + # `QIC()` refits the stored call with independence correlation. + expect_number(geepack::QIC(result)[["QIC"]]) +}) + +test_that("geelm with independence matches glm and geepack", { + result <- fit_geelm("independence") + glm_fit <- stats::glm(geelm_formula, data = geelm_data, family = stats::binomial()) + expect_equal(coef(result), coef(glm_fit), tolerance = 1e-8) + expect_identical(result$geese$alpha, 0) + + withr::with_options(opts_partial_match_old, { + geeglm_fit <- geepack::geeglm( + geelm_formula, + id = .id, waves = .waves, data = geelm_data, + family = stats::binomial(), corstr = "independence", scale.fix = TRUE + ) + expect_equal(vcov(result), vcov(geeglm_fit), tolerance = 1e-8, ignore_attr = TRUE) + }) +}) + +test_that("geelm with exchangeable correlation is close to geepack", { + result <- fit_geelm("exchangeable") + geeglm_fit <- withr::with_options(opts_partial_match_old, { + geepack::geeglm( + geelm_formula, + id = .id, waves = .waves, data = geelm_data, + family = stats::binomial(), corstr = "exchangeable", scale.fix = TRUE + ) + }) + # The correlation moment estimators differ slightly between the two packages. + expect_equal(coef(result), coef(geeglm_fit), tolerance = 1e-3) + expect_equal(result$geese$alpha, geeglm_fit$geese$alpha, tolerance = 0.05, ignore_attr = TRUE) +}) + +# Reference values below agree exactly with `geeasy::geelm()` version 0.1.3. + +test_that("geelm gives the expected results for exchangeable correlation", { + result <- fit_geelm("exchangeable") + expect_equal(unname(coef(result)), c(1.7931615, 0.7132700, 0.2043683, 1.3772946), tolerance = 1e-6) + expect_equal(unname(sqrt(diag(vcov(result)))), c(0.2769530, 0.3294433, 0.3238191, 0.5528630), tolerance = 1e-6) + expect_equal(result$geese$alpha, -0.0431269, tolerance = 1e-5) +}) + +test_that("geelm gives the expected results for AR1 correlation", { + result <- fit_geelm("ar1") + expect_equal(unname(coef(result)), c(1.7880949, 0.7161427, 0.2149498, 1.3645613), tolerance = 1e-6) + expect_equal(unname(sqrt(diag(vcov(result)))), c(0.2738198, 0.3294603, 0.3228504, 0.5518996), tolerance = 1e-6) + expect_equal(result$geese$alpha, -0.0072977, tolerance = 1e-4) +}) + +test_that("geelm gives the expected results for m-dependent correlation", { + result <- fit_geelm("m-dependent", mv = 2) + expect_equal(unname(coef(result)), c(1.7972223, 0.6958603, 0.1873876, 1.3984448), tolerance = 1e-6) + expect_equal(unname(sqrt(diag(vcov(result)))), c(0.2775508, 0.3296899, 0.3243606, 0.5533839), tolerance = 1e-6) + expect_equal(result$geese$alpha, c(-0.0064816, -0.1118319), tolerance = 1e-5) +}) + +test_that("geelm with 1-dependent correlation is close to AR1", { + # Same moment estimator for the lag-1 correlation, but a banded instead of AR1 working correlation. + result <- fit_geelm("m-dependent", mv = 1) + expected <- fit_geelm("ar1") + expect_length(result$geese$alpha, 1L) + expect_equal(coef(result), coef(expected), tolerance = 1e-4) + expect_equal(result$geese$alpha, expected$geese$alpha, tolerance = 1e-3) +}) + +test_that("geelm gives the expected results for unstructured correlation", { + result <- fit_geelm("unstructured") + expect_equal(unname(coef(result)), c(1.7582943, 0.6784657, 0.1705619, 1.3864354), tolerance = 1e-6) + expect_equal(unname(sqrt(diag(vcov(result)))), c(0.2786257, 0.3302633, 0.3256145, 0.5543606), tolerance = 1e-6) + expect_equal( + result$geese$alpha, + c(-0.0564589, -0.1257370, 0.0678152, -0.0835993, -0.0577740, 0.0092168), + tolerance = 1e-5 + ) +}) + +test_that("geelm results do not depend on the row order of the input data", { + expected <- fit_geelm("exchangeable") + set.seed(123) + perm <- sample(nrow(geelm_data)) + shuffled <- geelm_data[perm, ] + result <- fit_geelm("exchangeable", data = shuffled) + expect_equal(coef(result), coef(expected)) + expect_equal(vcov(result), vcov(expected)) + # Fitted values are returned in the order of the (complete) input data. + key <- function(d) paste(d$.id, d$.waves)[!is.na(d$FEV1_BINARY)] + reorder <- match(key(geelm_data), key(shuffled)) + expect_equal(unname(result$fitted.values[reorder]), unname(expected$fitted.values)) + expect_identical(result$id, shuffled$.id[!is.na(shuffled$FEV1_BINARY)]) +}) + +test_that("geelm drops observations with missing values", { + data <- geelm_data + rows <- which(!is.na(data$FEV1_BINARY))[c(2, 5, 10)] + data$FEV1_BINARY[rows[1:2]] <- NA + data$RACE[rows[3]] <- NA + result <- fit_geelm("exchangeable", data = data) + # Removing the rows creates gaps in the waves, hence the warning. + expected <- suppressWarnings(fit_geelm("exchangeable", data = data[-rows, ])) + expect_length(result$fitted.values, geelm_n_complete - 3L) + expect_length(result$prior.weights, geelm_n_complete - 3L) + expect_equal(coef(result), coef(expected)) + expect_equal(unname(result$fitted.values), unname(expected$fitted.values)) +}) + +test_that("summary works for geelm fits with dropped observations", { + data <- geelm_data + result <- fit_geelm("exchangeable", data = data) + expected <- suppressWarnings(fit_geelm("exchangeable", data = data[!is.na(data$FEV1_BINARY), ])) + expect_length(result$prior.weights, geelm_n_complete) + withr::with_options(opts_partial_match_old, { + expect_equal(stats::coef(summary(result)), stats::coef(summary(expected))) + }) +}) + +test_that("geelm estimates the dispersion when the scale is not fixed", { + result <- fit_geelm("exchangeable", control = geelm_control()) + fixed <- fit_geelm("exchangeable") + expect_false(result$geese$model$scale.fix) + expect_true(result$geese$gamma != 1) + expect_identical(fixed$geese$gamma, 1) +}) + +test_that("geelm converges to the same estimates from given initial values", { + expected <- fit_geelm("exchangeable") + init <- coef(expected) + 0.1 + result <- fit_geelm("exchangeable", control = geelm_control(scale.fix = TRUE, init.beta = init)) + expect_equal(coef(result), coef(expected), tolerance = 1e-5) +}) + +test_that("geelm without n-p correction gives a smaller correlation estimate in absolute value", { + result <- fit_geelm("exchangeable", control = geelm_control(scale.fix = TRUE, useP = FALSE)) + expected <- fit_geelm("exchangeable") + # The correction only changes the denominator of the moment estimator. + expect_lt(abs(result$geese$alpha), abs(expected$geese$alpha)) + expect_equal(coef(result), coef(expected), tolerance = 1e-3) +}) + +test_that("geelm works with a single cluster", { + data <- geelm_data[geelm_data$.id == geelm_ids_4[1], ] + data$FEV1_BINARY <- c(0L, 1L, 1L, 0L) + result <- geelm( + FEV1_BINARY ~ 1, + id = .id, waves = .waves, data = data, family = stats::binomial(), + corstr = "independence", control = geelm_control(scale.fix = TRUE) + ) + expect_equal(unname(coef(result)), 0, tolerance = 1e-8) +}) + +test_that("geelm warns for non-equidistant waves", { + data <- geelm_data + data$.waves[data$.waves == 4L] <- 10L + expect_warning( + result <- fit_geelm("exchangeable", data = data), + "Non-equidistant waves" + ) + # Only the ordering of the waves is used. + expect_equal(coef(result), coef(fit_geelm("exchangeable"))) +}) + +test_that("geelm fails for invalid inputs", { + expect_error(fit_geelm("toeplitz"), "should be one of") + expect_error(fit_geelm("m-dependent", mv = 1.5), "Mv must be an integer") + expect_error(fit_geelm("m-dependent", mv = 4), "Mv >= max\\(clustersize\\)") + expect_error( + geelm(geelm_formula, id = .id, waves = .waves, data = geelm_data, family = "binomial"), + "family must be a family object" + ) + data <- geelm_data + data$.waves <- as.character(data$.waves) + expect_error(fit_geelm("exchangeable", data = data), "waves must be numeric") +}) + +test_that("geelm fails for unstructured correlation with too few subjects", { + # 6 correlation parameters but only 5 subjects. + data <- geelm_data[geelm_data$.id %in% geelm_ids_4[1:5], ] + expect_error(fit_geelm("unstructured", data = data), "not enough subjects") +}) + +test_that("geelm fails for unstructured correlation with too few complete clusters", { + # Only 2 subjects (not more than 2 coefficients) have the largest cluster size. + data <- geelm_data[geelm_data$.id %in% geelm_ids_4[1:20], ] + data <- data[data$.waves <= 3L | data$.id %in% geelm_ids_4[1:2], ] + expect_error( + fit_geelm("unstructured", data = data, formula = FEV1_BINARY ~ ARMCD), + "Number of clusters of largest size is less than p" + ) +}) + +# geelm_fit ---- + +test_that("geelm_fit fails when the link of the mean response is not finite", { + x <- matrix(1, nrow = 4, dimnames = list(NULL, "(Intercept)")) + expect_error( + geelm_fit( + x = x, y = rep(0, 4), id = c(1, 1, 2, 2), offset = rep(0, 4), + family = stats::binomial(), weights = rep(1, 4), + control = geelm_control(scale.fix = TRUE), corstr = "independence" + ), + "Infinite or NaN in the link" + ) +}) + +test_that("geelm_fit fails when the variance of the mean response is not finite", { + family <- stats::poisson() + family$variance <- function(mu) rep(Inf, length(mu)) + x <- matrix(1, nrow = 4, dimnames = list(NULL, "(Intercept)")) + expect_error( + geelm_fit( + x = x, y = c(1, 2, 3, 4), id = c(1, 1, 2, 2), offset = rep(0, 4), + family = family, weights = rep(1, 4), + control = geelm_control(scale.fix = TRUE), corstr = "independence" + ), + "Infinite or NaN in the variance" + ) +}) + +test_that("geelm_fit fails for unsupported correlation structures", { + x <- matrix(1, nrow = 4, dimnames = list(NULL, "(Intercept)")) + expect_error( + geelm_fit( + x = x, y = c(0, 1, 1, 0), id = c(1, 1, 2, 2), offset = rep(0, 4), + family = stats::binomial(), weights = rep(1, 4), + control = geelm_control(scale.fix = TRUE), corstr = "fixed" + ), + "Unsupported correlation structure" + ) +}) + +test_that("geelm_fit warns when the algorithm does not converge", { + expect_warning( + fit_geelm("exchangeable", control = geelm_control(scale.fix = TRUE, maxit = 1)), + "Did not converge" + ) +}) + +test_that("geelm_fit warns when few clusters inform the m-dependent correlations", { + # Only 2 subjects (not more than 2 coefficients) have more than Mv = 2 observations. + data <- geelm_data[geelm_data$.id %in% geelm_ids_4[1:30], ] + data <- data[data$.waves <= 2L | data$.id %in% geelm_ids_4[1:2], ] + expect_warning( + fit_geelm("m-dependent", mv = 2, data = data, formula = FEV1_BINARY ~ ARMCD), + "very low sample size" + ) +}) + +test_that("geelm_fit can skip the sandwich estimator", { + d <- geelm_data[!is.na(geelm_data$FEV1_BINARY), ] + x <- stats::model.matrix(geelm_formula, d) + y <- d$FEV1_BINARY + result <- geelm_fit( + x = x, y = y, id = d$.id, offset = rep(0, nrow(d)), + family = stats::binomial(), weights = rep(1, nrow(d)), + control = geelm_control(scale.fix = TRUE, std.err = "naive"), corstr = "exchangeable" + ) + expect_class(result, "geelm_fit") + expect_identical(result$vbeta, as.matrix("no sandwich")) + expect_identical(dim(as.matrix(result$naiv.var)), c(4L, 4L)) + sandwich <- fit_geelm("exchangeable") + expect_equal(unname(result$beta), unname(coef(sandwich))) +}) diff --git a/vignettes/tern-gee.Rmd b/vignettes/tern-gee.Rmd index d4f94fe..e497038 100644 --- a/vignettes/tern-gee.Rmd +++ b/vignettes/tern-gee.Rmd @@ -38,7 +38,8 @@ by random effects in the model. This vignette shows the general purpose and syntax of the `tern.gee` R package which provides an interface for GEEs within the `tern` framework. This package builds upon some of the GEE functionality -included in the `geepack` and `geeasy` R packages. Within this package, +included in the `geepack` R package and adapts the GEE fitting engine +from the `geeasy` package. Within this package, we have implemented GEEs in R in such a way that they can easily be embedded into a `shiny` application. See `teal.modules.clinical::tm_a_gee()` and the [`teal.modules.clinical`