本文介绍了R:从下对角线制作对称矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要转换为dissim矩阵的矩阵的下三角形,因此它必须是对称的.

I have a lower triangular of a matrix that I'm trying to convert to a dissim matrix and thus it needs to be symmetric.

print(rdf)

         X0        X1        X2        X3 X4
0 0.0000000        NA        NA        NA NA
1 0.5340909 0.0000000        NA        NA NA
2 0.5340909 0.0000000 0.0000000        NA NA
3 0.3200000 0.5227273 0.5227273 0.0000000 NA
4 0.6263736 0.4945055 0.4945055 0.5384615  0

library(gdata)
upperTriangle(rdf) <- lowerTriangle(rdf)
isSymmetric(rdf)
       X0        X1        X2        X3        X4
0 0.0000000 0.5340909 0.5340909 0.6263736 0.4945055
1 0.5340909 0.0000000 0.3200000 0.0000000 0.5227273
2 0.5340909 0.0000000 0.0000000 0.5227273 0.4945055
3 0.3200000 0.5227273 0.5227273 0.0000000 0.5384615
4 0.6263736 0.4945055 0.4945055 0.5384615 0.0000000
[1] FALSE

这是怎么回事?注意,我不需要使用gdata

What is going on? Note, I don't need to use gdata

推荐答案

您需要确保要复制的元素正确排序:

You need to make sure that the elements you're copying are ordered correctly:

m <- matrix(NA,4,4)
m[lower.tri(m,diag=TRUE)] <- 1:10
     [,1] [,2] [,3] [,4]
[1,]    1   NA   NA   NA
[2,]    2    5   NA   NA
[3,]    3    6    8   NA
[4,]    4    7    9   10

makeSymm <- function(m) {
   m[upper.tri(m)] <- t(m)[upper.tri(m)]
   return(m)
}
makeSymm(m)

或者您可以使用内置的

Matrix::forceSymmetric(m,uplo="L")

这篇关于R:从下对角线制作对称矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 00:14