Creating a matrix based on a function from R
I have a symmetric matrix (size: 12,000 X 12,000) named A and I want to create another one based on a formula that depends on the position of the elements. Explain: I want to create a matrix D (based on the values ββfrom A) using the formula:
Dij = 1 - (aij/sqrt(aii*ajj))
Small example A:
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 this?
+3
source to share
3 answers
Is this 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
+5
source to share
cov2cor
is the way to go, but you can use the fact that aii
and are ajj
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
+3
source to share
You can use a vector R
to perform a task without explicit loops:
B <- matrix(rep(diag(A), ncol(A)), ncol(A))
C <- matrix(rep(diag(A), ncol(A)), ncol(A), byrow= TRUE)
D <- 1 - (A/sqrt(B*C))
#which gives
D
#
# [,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
+2
source to share