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.