Search code examples
rdataframecovariance-matrix

constructing variance-covariance matrix from pairwise correlation data in R


I have all the pairwise correlations and would like to construct the var-covariance matrix in order to do some standard analysis on that matrix. Here's a sample data for the covariances, the first two columns are the "ids" while the third column shows the covariance between the "ids".

data<-data.frame("id1" = c("a","b","c","a","a","b"),
                 "id2" = c("a","b","c","b","c","c"),
                 "cov"=c(1,1,1,0.1,0.3,0.4))

Solution

  • Base-R solution:

    nm <- unique(data$id1)   ## row/col names
    v <- matrix(NA,length(nm),length(nm),dimnames=list(nm,nm))  ## set up template
    v[cbind(data$id1,data$id2)] <- data$cov  ## fill in upper triangle
    v[is.na(v)] <- t(v)[is.na(v)]            ## symmetrize