Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a matrix based on a function in R

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?

like image 370
PaulaF Avatar asked Jun 17 '26 02:06

PaulaF


2 Answers

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
like image 198
Robert Avatar answered Jun 20 '26 00:06

Robert


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
like image 44
Rorschach Avatar answered Jun 19 '26 22:06

Rorschach