Search code examples
rarraysmatrixr-colnamesr-rownames

Is there a way to name column names or rownames?


, , RE

     Midterm Final mean
A       81.9  75.1 78.5
B       78.3  69.2 73.8
C       79.6  74.4 77.0
mean    79.9  72.9 76.4

I'm trying to name the rows and columns so that "Subject" is above the rows "A,B,C, and mean", and "Exam" is above the columns. I'd also like the header to be "Initial = RE" instead of just "RE".


Solution

  • To construct an array with named dimnames, pass a named list as the dimnames argument of matrix or array:

    x <- array(seq_len(18L), dim = c(3L, 3L, 2L),
               dimnames = list(D1 = letters[1:3], D2 = letters[4:6], D3 = letters[7:8]))
    x
    ## , , D3 = g
    ## 
    ##    D2
    ## D1  d e f
    ##   a 1 4 7
    ##   b 2 5 8
    ##   c 3 6 9
    ## 
    ## , , D3 = h
    ## 
    ##    D2
    ## D1   d  e  f
    ##   a 10 13 16
    ##   b 11 14 17
    ##   c 12 15 18
    

    To modify an existing array so that it has named dimnames, set the names attribute of the dimnames attribute:

    y <- array(seq_len(18L), dim = c(3L, 3L, 2L),
               dimnames = list(letters[1:3], letters[4:6], letters[7:8]))
    names(dimnames(y)) <- c("D1", "D2", "D3")
    
    identical(x, y)
    ## [1] TRUE
    

    However, note that names(dimnames(y)) <- value will not work if dimnames(y) is NULL:

    z <- array(seq_len(18L), dim = c(3L, 3L, 2L))
    names(dimnames(z)) <- c("D1", "D2", "D3")
    ## Error in names(dimnames(z)) <- c("D1", "D2", "D3") : 
    ##   attempt to set an attribute on NULL
    

    To get named but "empty" dimnames in the above case, you would have to do something like

    dimnames(z) <- list(D1 = NULL, D2 = NULL, D3 = NULL)
    

    or equivalently

    dimnames(z) <- setNames(vector("list", 3L), c("D1", "D2", "D3"))
    

    Now:

    z
    ## , , 1
    ## 
    ##       D2
    ## D1     [,1] [,2] [,3]
    ##   [1,]    1    4    7
    ##   [2,]    2    5    8
    ##   [3,]    3    6    9
    ## 
    ## , , 2
    ## 
    ##       D2
    ## D1     [,1] [,2] [,3]
    ##   [1,]   10   13   16
    ##   [2,]   11   14   17
    ##   [3,]   12   15   18
    

    It is interesting that we don't see D3 = 1 and D3 = 2 in the print output. That might be a bug - I'd have to ask the people upstairs.