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

R Array Indexing

Array indexing picks slices and single cells out of an array. A blank position in the brackets keeps every value along that dimension.

Pick one slice

The last position holds 2 and the other two stay blank. The result is the second slice as a plain matrix.

arr <- array(1:12, dim = c(3, 2, 2))
print(arr[, , 2])

One row from every slice

The first position is fixed at 1 and the other two stay blank. Each column of the result holds row 1 of one slice.

arr <- array(1:12, dim = c(3, 2, 2))
print(arr[1, , ])

Pick a single cell

A number for every dimension picks exactly one cell. The cell at row 2, column 1 of slice 2 holds 8.

arr <- array(1:12, dim = c(3, 2, 2))
print(arr[2, 1, 2])

One cell across slices

Two positions are fixed and the slice position stays blank. Both fixed dimensions drop away and a plain vector comes back.

arr <- array(1:12, dim = c(3, 2, 2))
print(arr[1, 1, ])

Keep the fixed dimension

drop = FALSE keeps the fixed first dimension in the result. The print still shows two slices, each with one row.

arr <- array(1:12, dim = c(3, 2, 2))
print(arr[1, , , drop = FALSE])

Example

arr <- array(1:12, dim = c(2, 3, 2))
print(arr[, , 1])
print(arr[2, 3, 2])
print(arr[1, , 2])

Key points

  • One position sits inside the brackets for each dimension.
  • A blank position keeps the whole dimension.
  • Fixing the last dimension picks one whole slice.
  • Giving a number for every dimension picks a single cell.
  • A dimension fixed at one position drops out of the result.
  • The drop = FALSE form keeps a fixed dimension in the result.

In this example the first print takes the whole first slice. The second print takes the single cell at row 2, column 3 of the second slice. The last print takes row 1 of the second slice across all three columns.

Note

Index counting starts at 1 on every dimension.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท rdrr.io R Snippets

Exercise

What does arr[2, 1, 2] pick from an array?