R Arrays

An array extends the idea of a matrix beyond two dimensions, letting you store data in three or more dimensions at once.

What Is an Array?

Where a vector is one-dimensional and a matrix is two-dimensional, an array can have any number of dimensions. A common use is stacking several matrices of the same shape into a single three-dimensional block, such as tracking a grid of values across several days.

Example

arr <- array(1:24, dim = c(2, 3, 4))
arr

dim(arr)

Reading an Array's Shape

The dim argument passed to array() lists the size of each dimension in order: rows, then columns, then however many "layers" (sometimes called slices) you want stacked behind them. array(1:24, dim = c(2, 3, 4)) creates 4 layers, each a 2-row by 3-column matrix.

Inspecting Dimensions

arr <- array(1:24, dim = c(2, 3, 4))

nrow(arr)
ncol(arr)
dim(arr)[3]
  • A vector has one dimension: length only
  • A matrix has two dimensions: rows and columns
  • An array has two or more dimensions: rows, columns, and one or more additional layers

Accessing Array Elements

Indexing an array follows the same bracket pattern as a matrix, just with one extra index per extra dimension: array[row, column, layer]. Leaving any position blank selects everything along that dimension.

Slicing an Array

arr <- array(1:24, dim = c(2, 3, 4))

arr[1, 2, 3]
arr[, , 1]
arr[1, , ]
StructureDimensionsCreated with
Vector1c()
Matrix2matrix()
Array2 or morearray()
Note: A matrix is really just a special case of an array with exactly two dimensions - matrix(1:6, nrow = 2) and array(1:6, dim = c(2, 3)) produce equivalent data, and class() calls a matrix both "matrix" and "array".

Exercise: R Arrays

How does an R array fundamentally differ from an R matrix?