๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

R Arrays

An array holds values in a grid with two or more dimensions. A matrix is the two dimension case of an array.

Build an array with three dimensions

The values 1 to 8 fill an array with two rows, two columns and two slices. The print shows one slice after the other.

cubes <- array(1:8, dim = c(2, 2, 2))
print(cubes)

Read the dimensions

dim reports one size for each dimension. The three numbers match the sizes passed to the array call.

cubes <- array(1:8, dim = c(2, 2, 2))
print(dim(cubes))

Values fill the first dimension first

The first three values run down the first column of the first slice. Later values move on to the second column and then the second slice.

grid <- array(1:12, dim = c(3, 2, 2))
print(grid)

Count the values

dim gives the shape of the array and length gives the total count. The total is the product of the three sizes.

tall <- array(1:24, dim = c(2, 3, 4))
print(dim(tall))
print(length(tall))

Example

boxes <- array(1:12, dim = c(2, 2, 3))
print(boxes)
print(dim(boxes))

Key points

  • array builds an array from a vector of values.
  • The dim value in the call gives the size of each dimension.
  • dim reports the size of each dimension of an array.
  • Values fill the first dimension first, then move to the next one.
  • An array with three dimensions prints one matrix slice at a time.
  • length counts every value stored in the array.

In this example the array holds twelve values in two rows, two columns and three slices. The print shows the three slices one at a time. The dim print confirms the shape 2, 2 and 3.

Note

The values in one array all share one type, like the values in a vector.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does print(dim(arr)) show for an array built with dim = c(2, 2, 2)?