Skip to content

Instantly share code, notes, and snippets.

@nilforooshan
Created June 20, 2024 08:26
Show Gist options
  • Save nilforooshan/c0877d8c4ee5a25b8963cdbefb45067f to your computer and use it in GitHub Desktop.
Save nilforooshan/c0877d8c4ee5a25b8963cdbefb45067f to your computer and use it in GitHub Desktop.
R: Replace the upper triangle of a covariance matrix with a correlation matrix

Replace the upper triangle of a covariance matrix with a correlation matrix

(x <- matrix(c(1,0.2,0.5,1.2,0.2,2,0.5,1,0.5,0.5,3,1.6,1.2,1,1.6,4), nrow = 4))
     [,1] [,2] [,3] [,4]
[1,]  1.0  0.2  0.5  1.2
[2,]  0.2  2.0  0.5  1.0
[3,]  0.5  0.5  3.0  1.6
[4,]  1.2  1.0  1.6  4.0
cov2cor(x)
          [,1]      [,2]      [,3]      [,4]
[1,] 1.0000000 0.1414214 0.2886751 0.6000000
[2,] 0.1414214 1.0000000 0.2041241 0.3535534
[3,] 0.2886751 0.2041241 1.0000000 0.4618802
[4,] 0.6000000 0.3535534 0.4618802 1.0000000
cov2corcov <- function(x) {
    y <- cov2cor(x)
    x[upper.tri(x)] <- y[upper.tri(y)]
    return(x)
}

cov2corcov(x)
     [,1]      [,2]      [,3]      [,4]
[1,]  1.0 0.1414214 0.2886751 0.6000000
[2,]  0.2 2.0000000 0.2041241 0.3535534
[3,]  0.5 0.5000000 3.0000000 0.4618802
[4,]  1.2 1.0000000 1.6000000 4.0000000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment