[R] R code for var-cov matrix given variances and correlations
Haynes, Maurice (NIH/NICHD)
haynesm at cfr.nichd.nih.gov
Tue Dec 21 14:09:43 CET 2004
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)?
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))
[1] 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[1]
vmat[1,2] <- cor[1] * (var[1]^.5 * var[2]^.5)
vmat[2,1] <- cor[1] * (var[2]^.5 * var[1]^.5)
vmat[2,2] <- var[2]
}
if (p == 3) {
vmat[1,1] <- var[1]
vmat[1,2] <- cor[1] * (var[1]^.5 * var[2]^.5)
vmat[1,3] <- cor[2] * (var[1]^.5 * var[3]^.5)
vmat[2,1] <- cor[1] * (var[2]^.5 * var[1]^.5)
vmat[2,2] <- var[2]
vmat[2,3] <- cor[3] * (var[2]^.5 * var[3]^.5)
vmat[3,1] <- cor[2] * (var[3]^.5 * var[1]^.5)
vmat[3,2] <- cor[3] * (var[3]^.5 * var[2]^.5)
vmat[3,3] <- var[3]
}
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
More information about the R-help
mailing list