I have an adjacency matrix:
myV = c(0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
0,1,1,0,0,0,0,0,0,0,
1,1,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,
1,1,0,0,1,1,0,0,0,0,
1,0,0,1,0,1,0,0,0,0,
0,0,1,0,0,0,0,0,0,0,
0,0,0,0,0,1,0,1,0,0);
myA = matrix(myV, nrow=10, byrow=TRUE);
rownames(myA) = colnames(myA) = paste0("P.",1:10);
myA;
That I want to sort jointly by rows and columns.
I can sort independently by rows, then columns ... or columns, then rows.
# row sort
rs = rowSums(myA);
rs.s = sort(rs);
rs.idx = as.numeric( gsub("P.","",names(rs.s)) );
myA.s = myA[rs.idx,];
myA.s;
Outputs:
P.1 P.2 P.3 P.4 P.5 P.6 P.7 P.8 P.9 P.10
P.1 0 0 0 0 0 0 0 0 0 0
P.2 0 0 0 0 0 0 0 0 0 0
P.3 0 0 0 0 0 0 0 0 0 0
P.6 0 0 0 0 0 0 0 0 0 0
P.9 0 0 1 0 0 0 0 0 0 0
P.4 0 1 1 0 0 0 0 0 0 0
P.5 1 1 0 0 0 0 0 0 0 0
P.10 0 0 0 0 0 1 0 1 0 0
P.8 1 0 0 1 0 1 0 0 0 0
P.7 1 1 0 0 1 1 0 0 0 0
And
cs = colSums(myA.s);
cs.s = sort(cs);
cs.idx = as.numeric( gsub("P.","",names(cs.s)) );
myA.ss = myA.s[,cs.idx];
myA.ss;
Outputs:
P.7 P.9 P.10 P.4 P.5 P.8 P.3 P.1 P.2 P.6
P.1 0 0 0 0 0 0 0 0 0 0
P.2 0 0 0 0 0 0 0 0 0 0
P.3 0 0 0 0 0 0 0 0 0 0
P.6 0 0 0 0 0 0 0 0 0 0
P.9 0 0 0 0 0 0 1 0 0 0
P.4 0 0 0 0 0 0 1 0 1 0
P.5 0 0 0 0 0 0 0 1 1 0
P.10 0 0 0 0 0 1 0 0 0 1
P.8 0 0 0 1 0 0 0 1 0 1
P.7 0 0 0 0 1 0 0 1 1 1
As an adjacency matrix, that is not exactly what I want ... The rows and cols don't match... e.g., P.1 as a row and P.1 as a column needs to be in the same location. Adjacency matrix. Symmetry.
So how do I sort simultaneously (jointly), I would like to be able to block it into partions of zero sub-matrices.
In this example, I am looking for an answer like 1,2,3,6 (rowSum=0, do I care about ties if I need symmetry?) ... 4,5,8 (colSum != 0 && rowSum !=0, natural order for symmetry?) ... 7,9,10 (colSum=0, natural order again, or use rowSum to sort on ties).
The goal is to place the most dense "block" in the bottom-left hand corner of the matrix ... And the current correct answer 1,2,3,6 ... 4,5,8 ... 7,9,10 may not accomplish that. Or maybe it does given the symmetry constraint.
Obviously I am looking for a function or code for a generalized solution and offer this example to demonstrate my need. I would prefer a solution using base
R that accomplishes this block sorting so the "top" and the "right" has sub-grids of zero matrices, and the adjacency symmetry is maintained. A general c-based solution I could port, if given the correct pseudo-code logic.
How to accomplish this?
Something like: myA[order,order];
... how to build order
?