array

array(data, dim)
The array function is used to create multidimensional arrays. For instance, a 3-D array is like a rectangular cube of numbers. A 4-D array could be thought of a matrix of matrices, where each of those sub-matrices has the same number of dimensions.
  • data – Data to fill the array, often a vector of values. Or if the vector is to be filled in later, perhaps simply NA.
  • dim – A vector describing the dimensions of the array. The length of the vector describes the number of array dimensions, e.g. an array with two dimensions is a regular matrix.

Example. Below we create an array with three dimensions. We show how the data is filled into the array by counting through the first 5 entries, then we print out the entire array.
> a <- array(1:(2*2*3), c(2,2,3))
> a[1,1,1]
[1] 1
> a[2,1,1]
[1] 2
> a[1,2,1]
[1] 3
> a[2,2,1]
[1] 4
> a[1,1,2]
[1] 5
> a
, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 3

     [,1] [,2]
[1,]    9   11
[2,]   10   12
Notice that the entries in the array are accessed in a similar way to that of a matrix. We could also access sections of the array by leaving out the number in the brackets in one or more dimensions, much like we do with matrices:
> a[,,1]
     [,1] [,2]
[1,]    1    3
[2,]    2    4
Tip. Arrays are the generalized form of vectors and matrices. Pay very close attention to which dimensions correspond to what. It can be helpful to store a lot of data in an array if it it fits the array structure and the meanings of each dimension are clear.

Leave a Reply