Skip to content

R - Arrays

In R, an array is a data structure that stores data in more than two dimensions. It is essentially a multi-dimensional extension of a vector, meaning all elements within an array must be of the same data type.

For example, a 3D array with dimensions (rows=2, cols=3, depth=4) can be visualized as 4 matrices, each having 2 rows and 3 columns. While powerful for specific applications like scientific computing or image processing, arrays are less common in general data analysis than data frames and tibbles, which are optimized for 2D tabular data.

You create an array using the array() function, which takes a vector of data and a dim argument specifying the dimensions.

# Create a vector of data. The length should be the product of the dimensions (2*3*2=12).
# We'll create data for two 2x3 matrices.
matrix_data_1 <- c(5, 9, 3, 10, 11, 12)
matrix_data_2 <- c(13, 14, 15, 6, 0, 1)
all_data <- c(matrix_data_1, matrix_data_2)
# Create an array with 2 rows, 3 columns, and 2 'layers' (matrices)
result_array <- array(all_data, dim = c(2, 3, 2))
print(result_array)

This creates the following output. Note how R fills the array by column, then row, then the next dimension.

, , 1
[,1] [,2] [,3]
[1,] 5 3 11
[2,] 9 10 12
, , 2
[,1] [,2] [,3]
[1,] 13 15 0
[2,] 14 6 1

For clarity, it’s a best practice to name the dimensions using the dimnames argument, which takes a list of character vectors.

# Define names for each dimension
row_names <- c("ROW1", "ROW2")
col_names <- c("COL1", "COL2", "COL3")
matrix_names <- c("Sensor_A", "Sensor_B")
# Re-create the array with named dimensions
named_array <- array(all_data, dim = c(2, 3, 2), dimnames = list(row_names, col_names, matrix_names))
print(named_array)

The output is now much more readable:

, , Sensor_A
COL1 COL2 COL3
ROW1 5 3 11
ROW2 9 10 12
, , Sensor_B
COL1 COL2 COL3
ROW1 13 15 0
ROW2 14 6 1

You access elements using square brackets [row, column, layer, ...]. Leaving a dimension blank selects all elements along that dimension.

# Get the element in the 1st row, 3rd column of the 2nd matrix ('Sensor_B')
print(named_array[1, 3, 2])
# Get the entire second row from the first matrix ('Sensor_A')
print(named_array[2, , 1])
# Get the entire second matrix ('Sensor_B')
print(named_array[, , 2])
# Add the two matrices together element-wise
matrix_sum <- named_array[, , 1] + named_array[, , 2]
print(matrix_sum)

The output of these operations:

[1] 0
COL1 COL2 COL3
9 10 12
COL1 COL2 COL3
ROW1 13 15 0
ROW2 14 6 1
COL1 COL2 COL3
ROW1 18 18 11
ROW2 23 16 13

Calculations Across Array Elements with apply()

Section titled “Calculations Across Array Elements with apply()”

The apply() function is a powerful tool for applying a function across the margins (dimensions) of an array.

Syntax: apply(X, MARGIN, FUN)

  • X: The array.
  • MARGIN: The dimension(s) to apply the function over. 1 for rows, 2 for columns, c(1, 2) for rows and columns, etc.
  • FUN: The function to apply (e.g., sum, mean).
# Calculate the sum of each row, across all matrices
# The result is the sum of ROW1s and the sum of ROW2s
row_sums <- apply(named_array, 1, sum)
print(row_sums)
# Calculate the mean of each column, across all matrices
# The result is the mean of COL1s, COL2s, and COL3s
col_means <- apply(named_array, 2, mean)
print(col_means)

Output:

ROW1 ROW2
47 52
COL1 COL2 COL3
10.25 8.50 6.00

Modern Perspective: When to Use Arrays vs. Tidy Data

Section titled “Modern Perspective: When to Use Arrays vs. Tidy Data”

While arrays are necessary for multi-dimensional data, most data analysis tasks benefit from a tidy data format, where:

  1. Each variable forms a column.
  2. Each observation forms a row.
  3. Each type of observational unit forms a table.

An array can be converted into a tidy tibble (a modern data frame). This makes it compatible with tools like dplyr and ggplot2.

# install.packages("tibble") # Run once
library(tibble)
library(dplyr)
# Convert the array to a tidy tibble
tidy_array <- as_tibble(as.data.frame.table(named_array))
# Rename the columns for clarity
tidy_array <- tidy_array %>%
rename(Row = Var1, Column = Var2, Sensor = Var3, Value = Freq)
print(tidy_array)
# Now, we can use dplyr to perform the same row sum calculation as apply()
summarized_data <- tidy_array %>%
group_by(Row) %>%
summarize(TotalValue = sum(Value))
print(summarized_data)

Guideline: Use arrays when the N-dimensional structure and positional access are critical (e.g., matrix algebra, image analysis). For most statistical analysis and visualization, convert your data to a tidy format first.