R/cor_to_spcor.R

Defines functions cor_to_spcor

Documented in cor_to_spcor

#' @rdname cor_to_pcor
#' @export
cor_to_spcor <- function(cor = NULL, cov = NULL, tol = .Machine$double.eps^(2 / 3)) {
  cor <- .get_cor(cor, cov)

  # Semi-partial
  if (is.null(cov)) {
    insight::format_error("Covariance matrix (or vector of SD of variables) needs to be passed for semi-partial correlations.")
  } else {
    if (!is.matrix(cov)) {
      cov <- cor_to_cov(cor, sd = cov)
    }
    inverted <- .invert_matrix(cov, tol = tol)
    out <- -stats::cov2cor(inverted) / sqrt(diag(cov)) / sqrt(abs(diag(inverted) - t(t(inverted^2) / diag(inverted))))
  }

  diag(out) <- 1
  out
}

Try the correlation package in your browser

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

correlation documentation built on April 6, 2023, 5:18 p.m.