I have a symmetric matrix (dimension: 12,000 X 12,000) named A and I want to create another one based on a formula, which depends on the elements position. To explain: I want to create the D matrix (based on the values from A) using the formula:
Dij = 1 - (aij/sqrt(aii*ajj))
A small example of A is:
A = matrix(c(1,0.5,0.4,0.3,0.2,0.5,1.1,0.5,0.4,0.3,0.4,0.5,1.2,0.5,0.6,0.3,0.4,0.5,1,0.2,0.2,0.3,0.6,0.2,1.2),ncol=5,nrow=5, byrow=T)
As I have a huge matrix, what would be the best way to do that?
Is that what you want?
1-cov2cor(A)
[,1] [,2] [,3] [,4] [,5]
[1,] 0.0000000 0.5232687 0.6348516 0.7000000 0.8174258
[2,] 0.5232687 0.0000000 0.5648059 0.6186150 0.7388835
[3,] 0.6348516 0.5648059 0.0000000 0.5435645 0.5000000
[4,] 0.7000000 0.6186150 0.5435645 0.0000000 0.8174258
[5,] 0.8174258 0.7388835 0.5000000 0.8174258 0.0000000
cov2cor is the way to go, but you can exploit the fact that aii and ajj are always on the diagonal of your matrix.
1 - A/sqrt(outer(diag(A), diag(A), `*`))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0.0000000 0.5232687 0.6348516 0.7000000 0.8174258
# [2,] 0.5232687 0.0000000 0.5648059 0.6186150 0.7388835
# [3,] 0.6348516 0.5648059 0.0000000 0.5435645 0.5000000
# [4,] 0.7000000 0.6186150 0.5435645 0.0000000 0.8174258
# [5,] 0.8174258 0.7388835 0.5000000 0.8174258 0.0000000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With