How to Use Dimensions to Extract Values from an Array in R - dummies

How to Use Dimensions to Extract Values from an Array in R

By Andrie de Vries, Joris Meys

Extracting values from an array in R with any number of dimensions is completely equivalent to extracting values from a matrix. You separate the dimension indices you want to retrieve with commas.

If necessary you can use the drop argument exactly as you do with matrices. For example, to get the value from the second row and third column of the first table of my.array, you simply do the following:

> my.array[2,3,1]
[1] 8

If you want the third column of the second table as an array, you use the following code:

> my.array[, 3, 2, drop=FALSE]
, , 1
[1,]  19
[2,]  20
[3,]  21

If you don’t specify the drop=FALSE argument, R will try to simplify the object as much as possible. This also means that if the result has only two dimensions, R will make it a matrix. The following code returns a matrix that consists of the second row of each table:

> my.array[2, , ]
   [,1] [,2]
[1,]  2  14
[2,]  5  17
[3,]  8  20
[4,]  11  23

This reduction doesn’t mean, however, that rows stay rows. In this case, R made the rows columns. This is due to the fact that R first selects the values, and then adds the dimensions necessary to represent the data correctly.

In this case R needs two dimensions with four indices (the number of columns) and two indices (the number of tables), respectively. As R fills a matrix column-wise, the original rows now turned into columns.