R/Correlation.R

Defines functions CorrAnalysis

Documented in CorrAnalysis

#' @title Correlation Analysis with P-value Matrix and Heatmap
#'
#' @description
#' Computes the correlation matrix along with corresponding p-values
#' and visualizes the correlations using a heatmap.
#'
#' @param data A numeric data frame or matrix containing variables
#' (e.g., one dependent variable y and multiple independent variables x).
#'
#' @return A list containing:
#' \itemize{
#'   \item correlation_matrix: Numeric correlation matrix
#'   \item p_value_matrix: Formatted p-value matrix (character)
#' }
#'
#' @import Hmisc corrplot
#' @importFrom stats cor
#' @export
CorrAnalysis <- function(data) {

  if (!is.data.frame(data) && !is.matrix(data)) stop("data must be a data frame or matrix")
  if (!all(sapply(data, is.numeric))) stop("All variables must be numeric")

  cor_matrix <- cor(data, use = "complete.obs")
  res <- Hmisc::rcorr(as.matrix(data))
  p_mat <- res$P

  p_mat_char <- matrix("", nrow = ncol(p_mat), ncol = ncol(p_mat))
  colnames(p_mat_char) <- colnames(p_mat)
  rownames(p_mat_char) <- rownames(p_mat)

  for(i in 1:nrow(p_mat)){
    for(j in 1:ncol(p_mat)){
      p_val <- p_mat[i, j]
      if(i == j || p_val < 0.001) {
        p_mat_char[i, j] <- "<0.001"
      } else {
        p_mat_char[i, j] <- round(p_val, 3)
      }
    }
  }

  message("\nCorrelation Matrix:\n")
  print(round(cor_matrix, 3))

  message("\nFormatted P-value Matrix:\n")
  print(p_mat_char)

  oldpar <- graphics::par(no.readonly = TRUE)
  on.exit(graphics::par(oldpar))

  graphics::par(family = "serif", font = 2)

  corrplot::corrplot(cor_matrix,
                     method = "color",
                     type = "upper",
                     tl.col = "black",
                     tl.srt = 45,
                     tl.cex = 1.2)

  invisible(list(
    correlation_matrix = cor_matrix,
    p_value_matrix = p_mat_char
  ))
}

Try the linreg package in your browser

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

linreg documentation built on April 17, 2026, 1:07 a.m.