Search code examples
rxtable

How to convert from a matrix to a contingency table?


I have the following matrix

matrix(c(1228,39,2,158,100,649,1,107,1,0,54,9,73,12,4,137), nrow=4)
    [,1] [,2] [,3] [,4]
[1,] 1228  100    1   73
[2,]   39  649    0   12
[3,]    2    1   54    4
[4,]  158  107    9  137

And I would like to convert it into a contingency table with named "axes" and ordered column names (basically keeping the existing ones column-row indexing). In other words, some like:

      Variable 1
        [,1] [,2] [,3] [,4]
    [1,] 1228  100    1   73
var2[2,]   39  649    0   12
    [3,]    2    1   54    4
    [4,]  158  107    9  137

Solution

  • You can assign dimnames when creating matrix

    m = matrix(c(1228,39,2,158,100,649,1,107,1,0,54,9,73,12,4,137), nrow=4)
    
    matrix(m, nrow = NROW(m), dimnames=list(var1 = sequence(NROW(m)), var2 = sequence(NCOL(m))))
    #    var2
    #var1    1   2  3   4
    #   1 1228 100  1  73
    #   2   39 649  0  12
    #   3    2   1 54   4
    #   4  158 107  9 137 
    

    In fact, you could use dimnames right at the start when creating m too