0

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
Dambo
  • 3,318
  • 5
  • 30
  • 79
  • 2
    `\`attr<-\`(m, "dimnames", list(var1 = 1:4, var2 = 1:4))` ? – Frank Apr 25 '17 at 00:48
  • @Frank thanks, not confident at all with the notation tho, what `attr<-` does? – Dambo Apr 25 '17 at 00:52
  • 1
    It creates a new object with one attribute modified, in this case its "dimnames". I found this attribute by looking at `str(table(a = 1:2, b = 1:2))`. – Frank Apr 25 '17 at 00:55

2 Answers2

0

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

d.b
  • 32,245
  • 6
  • 36
  • 77
0

We can use with dimnames and names

dimnames(m1) <- list(NULL, NULL)
names(dimnames(m1)) <- c("Var2", "Variable 1")
m1
#     Variable 1
#Var2   [,1] [,2] [,3] [,4]
#   [1,] 1228  100    1   73
#   [2,]   39  649    0   12
#   [3,]    2    1   54    4
#   [4,]  158  107    9  137

Or in one line

dimnames(m1) <- list(Var2 = NULL, `Variable 1` = NULL)

Or another way to write it

dimnames(m1) <- setNames(vector("list", 2), c("Var2", "Variable 1"))

data

m1 <- matrix(c(1228,39,2,158,100,649,1,107,1,0,54,9,73,12,4,137), nrow=4)
akrun
  • 874,273
  • 37
  • 540
  • 662