# [R] R code for var-cov matrix given variances and correlations

David Firth d.firth at warwick.ac.uk
Tue Dec 21 14:38:07 CET 2004

```On 21 Dec, 2004, at 13:09, Haynes, Maurice (NIH/NICHD) wrote:

> Dear list members,
>
> Where can I find code for computing the p*p variance-covariance
> matrix given a vector of p variances (ordered varA, varB, ...,
> varp) and a vector of all possible correlations (ordered corAB,
> corAC, ..., corp-1,p)?

Something like this (not tested):

sd.vec <- sqrt(var.vec)
n <- length(sd.vec)
cor.mat <- matrix(1, n, n)
for (i in 2:n){
for (j in 1:i-1){
cor.mat[i,j] <- cor.vec[(i-1)*(i-2)/2 + j]
cor.mat[j,i] <- cor.mat[i,j]}}
cov.mat <- cor.mat * outer(sd.vec, sd.vec)

I hope that helps.

David

>
> I know that the covariance between 2 variables is equal to the
> product of their correlation and their standard deviations:
> corAB * varA^.5 * varB^.5
> and so:
> covAB <- function(corAB, varA, varB) {
>     corAB * varA^.5 * varB^.5
>     }
>
> If the vector of variances were
> var.vec <- c(14, 12, 7)
> and the vector of correlations were
> cor.vec <- c(.4, .2, .5),
> then the vector of covariances would be:
>> covAB(c(.4, .2, .5),c(14, 14, 12), c(12, 7, 7))
>  5.184593 1.979899 4.582576
>>
> and the variance-covariance matrix with covariances rounded to
> the first decimal place would be:
>> vmat <- matrix(c(14, 5.2, 2.0, 5.2, 12, 4.6, 2.0, 4.6, 7),
> + nrow=3)
>> vmat
>      [,1] [,2] [,3]
> [1,] 14.0  5.2  2.0
> [2,]  5.2 12.0  4.6
> [3,]  2.0  4.6  7.0
>>
>
> So the question is: How can I generate a p*p variance-covariance
> matrix from a vector of variances and a vector of correlations
> without resorting to a construction like:
>     vmat <- matrix(rep(0, p*p), nrow=p)
>     if (p == 2) {
>         vmat[1,1] <- var
>         vmat[1,2] <- cor * (var^.5 * var^.5)
>         vmat[2,1] <- cor * (var^.5 * var^.5)
>         vmat[2,2] <- var
>         }
>     if (p == 3) {
>         vmat[1,1] <- var
>         vmat[1,2] <- cor * (var^.5 * var^.5)
>         vmat[1,3] <- cor * (var^.5 * var^.5)
>         vmat[2,1] <- cor * (var^.5 * var^.5)
>         vmat[2,2] <- var
>         vmat[2,3] <- cor * (var^.5 * var^.5)
>         vmat[3,1] <- cor * (var^.5 * var^.5)
>         vmat[3,2] <- cor * (var^.5 * var^.5)
>         vmat[3,3] <- var
>         }
> and so forth?
>
> Thanks,
>
> Maurice Haynes
> National Institute of Child Health and Human Development
> Child and Family Research Section
> 6705 Rockledge Drive, Suite 8030
> Bethesda, MD  20892
> Voice: 301-496-8180
> Fax: 301-496-2766
> E-mail: mh192j at nih.gov
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help