Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Last active March 13, 2024 02:50
Show Gist options
  • Save nilforooshan/8368d962659a9cb79e877e3b6775332f to your computer and use it in GitHub Desktop.
Save nilforooshan/8368d962659a9cb79e877e3b6775332f to your computer and use it in GitHub Desktop.
R: R function for converting correlations and variances to covariances

R function for converting correlations and variances to covariances

The R "stats" package provides the cov2cor function. However, there is no cor2cov function available.

cor2cov <- function(cor.mat, var.vec) {
    # Check inputs
    stopifnot(isSymmetric(cor.mat))
    stopifnot(identical(diag(cor.mat), rep(1, length(diag(cor.mat)))))
    stopifnot(is.vector(var.vec))
    stopifnot(length(var.vec)==nrow(cor.mat))
    stopifnot(all(var.vec > 0))
    # Start the job
    sd.mat = diag(sqrt(var.vec))
    return(sd.mat %*% cor.mat %*% sd.mat)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment