[R] R code for var-cov matrix given variances and correlations
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Tue Dec 21 14:34:59 CET 2004
"Haynes, Maurice (NIH/NICHD)" <haynesm at cfr.nichd.nih.gov> writes:
> 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
> >
# First fill in the correlation matrix:
V <- matrix(NA,3,3)
diag(V) <- 1
V[lower.tri(V)] <- c(.4, .2, .5)
V[upper.tri(V)] <- t(V)[upper.tri(V)]
# then scale rows and columns
D <- diag(sqrt( c(14, 12, 7)))
D %*% V %*% D
# or, more efficiently
s <- sqrt( c(14, 12, 7))
sweep(sweep(V,1,s,"*"),2,s,"*")
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list