简体   繁体   中英

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.

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.

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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