R Arrays

R Arrays

While matrices are strictly limited to two dimensions, Arrays can hold highly complex multi-dimensional data!

An array can have three, four, or even dozens of dimensions.


Creating an Array

To build an array, you utilize the array() function.

The most critical argument is dim (dimensions), where you pass a vector defining the exact shape.

For example, dim = c(2, 3, 2) creates two separate 2x3 matrices stacked behind each other in 3D space!

Creating an Array Example:

# A vector containing numbers 1 through 24
data_values <- c(1:24)
# Creates an array with 2 rows, 3 columns, across 4 layers (matrices)
my_array <- array(data_values, dim = c(2, 3, 4))

print(my_array)


Accessing Array Elements

Because arrays have more than two dimensions, accessing them requires more coordinates!

The syntax becomes [row, column, matrix_layer].

For instance, my_array[1, 2, 3] extracts the element from the 1st row, 2nd column, of the 3rd matrix layer.

Accessing Elements:

# Re-creating the array for this example
data_values <- c(1:24)
my_array <- array(data_values, dim = c(2, 3, 4))
# Extracting a single element
val <- my_array[2, 3, 1]
print(val)
# Extracting an entire matrix layer (leave row and col blank!)
layer_two <- my_array[, , 2]
print(layer_two)

Exercise 1 of 2

?

What is the primary difference between a Matrix and an Array in R?

Exercise 2 of 2

?

Which argument inside the array() function explicitly sets the array's shape and dimensions?