Generate covariance matrix from correlation matrix

前端 未结 4 1576
孤独总比滥情好
孤独总比滥情好 2021-02-05 20:36

I have a correlation matrix:

a <- matrix(c(1, .8, .8, .8, 1, .8, .8, .8, 1), 3)

##      [,1] [,2] [,3]
## [1,]  1.0  0.8  0.8
## [2,]  0.8  1.0  0.8
## [3,]          


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 21:29

    Building on S4M's answer, in base R, I would write this function:

    cor2cov <- function(V, sd) {
      V * tcrossprod(sd)
    }
    

    tcrossprod will calculate the product of each combination of elements of the sd vector (equivalent to x %*% t(x)), which we then (scalar) multiply by the variance-covariance matrix

    Here's a quick check that the function is correct using the built in mtcars data set:

    all.equal(
      cor2cov(cor(mtcars), sapply(mtcars, sd)), 
      cov(mtcars)
    )
    

提交回复
热议问题