问题描述
我搜索了相关问题以找到答案,但仍未提出解决方案.
I searched for related questions in order to find an answer, but couldn't come up with a solution, yet.
这是我的示例矩阵:
input <- structure(c(1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0), .Dim = c(3L,
5L), .Dimnames = list(c("X", "Y", "Z"), c("A", "B", "C", "D",
"E")))
我想根据输入矩阵的行将此矩阵转换为正方形矩阵.因此,我想要的输出应如下所示:
I want to transform this matrix into a square matrix based on rows of the input matrix. So my desired output should look like that:
output <- structure(c(1, 2, 0, 2, 1, 0, 0, 0, 1), .Dim = c(3L, 3L), .Dimnames = list(c("X", "Y", "Z"), c("X", "Y", "Z")))
当然,对角线取值为1.
where, of course, the diagonal takes the value of 1.
最重要的是:输出矩阵中i,j的值(如果i!= j)应对应于输入矩阵中同一列中非零值的数量.
What is most important: The values of i,j (if i != j) in the output matrix should correspond to the number of non-zero values in the same columns within the input matrix.
因此,X和Y的值应取值为2,因为X和Y在同一列A和B中的值都大于0.
So, the value for X and Y should take the value of 2, because both X and Y have values higher than 0 in the same columns A and B.
感谢您的努力.预先感谢!
I appreciate your effort. Thanks in advance!
推荐答案
只需将矩阵及其转置的矩阵相乘,然后将diag设置为1:
Just taking the matrix multiplication of the matrix and its transpose, then setting the diag to 1:
output <- input %*% t(input)
diag(output) <- 1
> output
X Y Z
X 1 2 0
Y 2 1 0
Z 0 0 1
这篇关于R DataFrame转换成方形(对称)矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!