Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

3 Dimensional Array Names in R

Tags:

arrays

r

names

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 ?

like image 630
RiskTech Avatar asked Aug 13 '14 17:08

RiskTech


People also ask

What is a 3 dimensional array in R?

A three-dimensional array can have matrices of different size and they are not necessarily to be square or rectangular. Also, all the elements in an array are of same data type.

What are 3D arrays called?

They are called Tensors, and in your case can be thought of as matrices whose entries are themselves matrices. Any higher dimensions are also called tensors and are distinguished by their "order" (number of dimensions)

How do I name a dimension in R?

dimnames in R: How to Use dimnames() Function in R. The rownames() method in R is used to set the names to rows of a matrix. The colnames() method in R is used to set the names to columns of a matrix. But these functions don't operate on both rows and columns at once, but dimnames() can.

How do I create a 3 D array in R?

Create 3D array using the dim() function in R 3 D array is also known as Multidimensional array. We can create a multidimensional array with dim() function. We can pass this dim as an argument to the array() function.


2 Answers

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")
like image 62
Dan Avatar answered Oct 04 '22 09:10

Dan


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
like image 12
susopeiz Avatar answered Oct 04 '22 08:10

susopeiz