Search code examples
rcovariance

How to organize a list of covariance pairs in a squared covariance matrix?


I am working in R and I have a tibble composed of three columns:

  • V1: the name of the first variable
  • V2: the name of the second variable
  • cov: the value of the covariance between V1 and V2.

This tibble is expanded over n columns for n covariance pairs.

I would like to get a matrix that looks like a classical covariance matrix, ie a square n x n matrix with the covariance pairs in it.

Any idea how could I implement this?


Solution

  • Something along the lines of

    ## find row/column names
    n <- unique(c(dd$V1,dd$V2))
    ## construct matrix  
    M <- matrix(NA, length(n),length(n), dimnames=list(n,n))
    ## fill in values
    M[cbind(dd$V1,dd$V2)] <- dd$V3
    

    If you only have the lower/upper triangle in your initial data set you'll need something like M[lower.tri(M)] <- t(M)[upper.tri(M)] to symmetrize ...