R/score_r2.R

Defines functions score_r2

Documented in score_r2

#' Compute R-squared between numeric observations and predictions
#'
#' @description
#' Internal function to compute the R-squared of observations versus predictions via \code{stats::cor()}. Used within [f_numeric_glm()], [f_numeric_gam()], [f_numeric_rf()], [f_count_glm()], and [f_count_gam()].
#'
#' @param o (required, numeric vector) Observations. Default: NULL
#' @param p (required, numeric vector) Predictions. Default: NULL
#' @inheritParams collinear
#'
#' @return numeric: Pearson R-squared
#' @export
#' @autoglobal
#' @family modelling_tools
#' @examples
#'   score_r2(
#'     o = c(1, 1, 1, 0.5, 0.5, 0, 0),
#'     p = c(1, 0.8, 0.7, 0.6, 0.5, 0.1, 0)
#'   )
score_r2 <- function(
  o = NULL,
  p = NULL,
  ...
) {
  function_name <- validate_arg_function_name(
    default_name = "collinear::score_r2()",
    ... = ...
  )

  out <- tryCatch(
    {
      stats::cor(
        x = p,
        y = o,
        use = "complete.obs",
        method = "pearson"
      )^2
    },
    error = function(e) {
      stop(
        "\n",
        function_name,
        ": ",
        conditionMessage(e),
        call. = FALSE
      )
    }
  )

  out
}

Try the collinear package in your browser

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

collinear documentation built on Dec. 8, 2025, 5:06 p.m.