3 Dimensional Array Names in R

时光毁灭记忆、已成空白 提交于 2019-11-30 07:23:16

问题


In the 3 Dimensional array bellow :

ar <- array(someData, c(5, 5, 5));  
rownames(ar) <- ...;  #to set up row names
colnames(ar) <- ...;  #to set up col names

How can i set the third dimension names ?


回答1:


You can either set the dimnames argument when defining the array:

ar <- array(data     = 1:27,
            dim      = c(3, 3, 3),
            dimnames = list(c("a", "b", "c"),
                            c("d", "e", "f"),
                            c("g", "h", "i")))

and/or you can set the dimnames of the third dimension like so:

dimnames(ar)[[3]] <- c("G", "H", "I")



回答2:


Still starting in R but I found this way that may be useful for large multidimensional array.

Instead of naming each of the indexes ('a','b','c','d',....), you can use provideDimnames() function to automatic generate the index names following the pattern you choose.

Creating data

ar <- array (data = 1:(4*3*2) , dim=c(4,3,2))
> ar
, , 1

     [,1] [,2] [,3]
[1,]    1    5    9
[2,]    2    6   10
[3,]    3    7   11
[4,]    4    8   12

, , 2

     [,1] [,2] [,3]
[1,]   13   17   21
[2,]   14   18   22
[3,]   15   19   23
[4,]   16   20   24

Labelling dimensions

ar <- provideDimnames(ar , sep = "_", base = list('row','col','lev'))

And you get

> ar
, , lev

      col col_1 col_2
row     1     5     9
row_1   2     6    10
row_2   3     7    11
row_3   4     8    12

, , lev_1

      col col_1 col_2
row    13    17    21
row_1  14    18    22
row_2  15    19    23
row_3  16    20    24


来源:https://stackoverflow.com/questions/25292739/3-dimensional-array-names-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!