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?

Asked on August 30, 2020 in R.
Add Comment
2 Answer(s)

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 …

Answered on August 30, 2020.
Add Comment

You could construct a sparse matrix:

DF <- data.frame(var1 = c("a", "a", "b", "a", "b", "c"),                   var2 = c("b", "c", "c", "a", "b", "c"),                   cov = c(0.1, 0.2, 0.3, 0.4, 0.5, 0.6)) DF$var1 <- factor(DF$var1, levels = sort(unique(c(DF$var1, DF$var2)))) DF$var2 <- factor(DF$var2, levels = levels(DF$var1))  library(Matrix) sparseMatrix(i = as.integer(DF$var1),               j = as.integer(DF$var2),               x = DF$cov,               dimnames = list(levels(DF$var1), levels(DF$var2)),              symmetric = TRUE) #3 x 3 sparse Matrix of class "dsCMatrix" #    a   b   c #a 0.4 0.1 0.2 #b 0.1 0.5 0.3 #c 0.2 0.3 0.6  

Use as.matrix to create a dense matrix if you need one.

Answered on August 30, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.