Correlation and Covariance

In probability theory and statistics, the mathematical descriptions of covariance and correlation are very similar. Both describe the degree of similarity between two random variables or sets of random variables. Notably, correlation is dimensionless while covariance is in units obtained by multiplying the units of the two considered variables. Although R has a built-in function cov2cor to convert covariance matrices into correlation matrices, there is no function to transpose a correlation matrix into a covariance matrix.

################################################################################
# Convert standard deviation and correlation to covariance
#
# sd      : Vector of length n with the standard deviations of each process.
#           n is the number of random processes.
# cor.mat : n-by-n correlation coefficient matrix.
################################################################################
# Author  : Thomas Debray
# Version : 5 jan 2010
################################################################################
 
cor2cov <- function(sd,cor.mat)
{
    if (dim(cor.mat)[1] != dim(cor.mat)[2])
        stop("'cor.mat' should be a square matrix")
    n <- sqrt(length(cor.mat))
    if (n != length(sd))
        stop("The length of 'sd' should be the same as the number of rows of 'cor.mat'")
    if (length(sd[sd > 0]) != n)
       stop("The elements in 'sd' should all be positive")
    if (length(cor.mat[diag(cor.mat)!=1]))
       stop("The diagonal of 'cor.mat' cannot contain values different from 1")
 
    cov.mat = array(NA,c(dim(cor.mat)[1],dim(cor.mat)[2]))
    for (i in 1:n) {
       for (j in 1:n) {
            cov.mat[i,j] = cor.mat[i,j]*sd[i]*sd[j]
       }
    }
    cov.mat
}

 

[ Back ]