Reputation: 271
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!
Upvotes: 0
Views: 880
Reputation: 6913
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
Upvotes: 3