基于R中的函数创建矩阵

时间:2015-06-16 01:17:53

标签: r matrix dataframe

我有一个名为A的对称矩阵(维度:12,000 X 12,000),我想根据公式创建另一个矩阵,这取决于元素的位置。解释: 我想使用以下公式创建D矩阵(基于A的值):

Dij = 1 - (aij/sqrt(aii*ajj))

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)

由于我有一个巨大的矩阵,最好的方法是什么?

3 个答案:

答案 0 :(得分:5)

这就是你想要的吗?

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

答案 1 :(得分:3)

cov2cor是可行的方法,但您可以利用aiiajj始终位于矩阵对角线的事实。

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

答案 2 :(得分:2)

您可以使用R的矢量化来完成任务,而无需任何显式循环:

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