R/r2_somers.R

Defines functions r2_somers

Documented in r2_somers

#' @title Somers' Dxy rank correlation for binary outcomes
#' @name r2_somers
#'
#' @description Calculates the Somers' Dxy rank correlation for logistic regression models.
#'
#' @param model A logistic regression model.
#'
#' @return A named vector with the R2 value.
#'
#' @examples
#' \donttest{
#' if (require("correlation") && require("Hmisc")) {
#'   model <- glm(vs ~ wt + mpg, data = mtcars, family = "binomial")
#'   r2_somers(model)
#' }
#' }
#'
#' @references Somers, R. H. (1962). A new asymmetric measure of association for
#'   ordinal variables. American Sociological Review. 27 (6).
#' @export
r2_somers <- function(model) {
  insight::check_if_installed("correlation")

  info <- insight::model_info(model, verbose = FALSE)
  if (!info$is_binomial) {
    insight::format_error("`r2_somers()` only accepts logistic regression models.")
  }

  input <- data.frame(
    y = .recode_to_zero(insight::get_response(model, verbose = FALSE)),
    pred = stats::predict(model, type = "response"),
    stringsAsFactors = FALSE
  )

  out <- correlation::cor_test(input, "y", "pred", method = "somers")

  r2somers <- out$Dxy
  names(r2somers) <- "Somers' Dxy"
  r2somers
}

Try the performance package in your browser

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

performance documentation built on Oct. 19, 2024, 1:07 a.m.