Arrays in R

An array can be considered as a multiply subscripted collection of data entries. This section provides details on the construction and manipulation of arrays.

The array() function

As well as giving a vector structure a dim attribute, arrays can be constructed from vectors by the array function, which has the form

> Z <- array(data_vector, dim_vector)

For example, if the vector h contains 24 or fewer, numbers then the command

> Z <- array(h, dim=c(3,4,2))

would use h to set up 3 by 4 by 2 array in Z. If the size of h is exactly 24 the result is the same as

> Z <- h ; dim(Z) <- c(3,4,2)

However if h is shorter than 24, its values are recycled from the beginning again to make it up to size 24 but dim(h) <- c(3,4,2) would signal an error about mismatching length. As an extreme but common example

> Z <- array(0, c(3,4,2))

makes Z an array of all zeros.

At this point dim(Z) stands for the dimension vector c(3,4,2), and Z[1:24] stands for the data vector as it was in h, and Z[] with an empty subscript or Z with no subscript stands for the entire array as an array.

Arrays may be used in arithmetic expressions and the result is an array formed by element-by-element operations on the data vector. The dim attributes of operands generally need to be the same, and this becomes the dimension vector of the result. So if A, B and C are all similar arrays, then

> D <- 2*A*B + C + 1

makes D a similar array with its data vector being the result of the given element-by-element operations. However the precise rule concerning mixed array and vector calculations has to be considered a little more carefully.


Mixed vector and array arithmetic. The recycling rule

The precise rule affecting element by element mixed calculations with vectors and arrays is somewhat quirky and hard to find in the references. From experience we have found the following to be a reliable guide.

  • The expression is scanned from left to right.
  • Any short vector operands are extended by recycling their values until they match the size of any other operands.
  • As long as short vectors and arrays only are encountered, the arrays must all have the same dim attribute or an error results.
  • Any vector operand longer than a matrix or array operand generates an error.
  • If array structures are present and no error or coercion to vector has been precipitated, the result is an array structure with the common dim attribute of its array operands.