简体   繁体   English

R DataFrame转换成方形(对称)矩阵

[英]R DataFrame into square (symmetric) matrix

I searched for related questions in order to find an answer, but couldn't come up with a solution, yet. 我搜索了相关问题以找到答案,但还没有找到解决方案。

So here is my example matrix: 所以这是我的示例矩阵:

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")))

where, of course, the diagonal takes the value of 1. 当然,对角线取值为1

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. 最重要的是:输出矩阵中i,j的值(如果i!= j)应对应于输入矩阵中同一列中非零值的数量。

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. 因此,X和Y的值应取值为2,因为在同一列A和B中X和Y的值均大于0。

I appreciate your effort. 感谢您的努力。 Thanks in advance! 提前致谢!

Just taking the matrix multiplication of the matrix and its transpose, then setting the diag to 1: 只需对矩阵及其转置进行矩阵乘法,然后将diag设置为1:

output <- input %*% t(input)
diag(output) <- 1

> output
  X Y Z
X 1 2 0
Y 2 1 0
Z 0 0 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM