R Arrays
An array extends the matrix concept to three or more dimensions. A matrix has rows and columns (2D). An array adds a third dimension — imagine stacking multiple matrices on top of each other, like pages in a book. All elements in an array must be the same data type.
The Dimension Concept
1D → Vector: [1, 2, 3, 4, 5]
single line of values
2D → Matrix: rows × columns
like a table
3D → Array: rows × columns × layers
like a stack of tables
Creating a 3D Array
arr <- array(1:24, dim = c(2, 3, 4)) # dim = c(rows, columns, layers) # 2 rows × 3 columns × 4 layers = 24 elements
Layer 1: Layer 2: Layer 3: Layer 4: [,1][,2][,3] [,1][,2][,3] [,1][,2][,3] [,1][,2][,3] 1 3 5 7 9 11 13 15 17 19 21 23 2 4 6 8 10 12 14 16 18 20 22 24
Naming Dimensions
# Sales data: 2 products, 3 regions, 2 years
sales_arr <- array(
data = c(100,200,150,250,300,180,120,220,160,270,310,195),
dim = c(2, 3, 2),
dimnames = list(
c("ProductA", "ProductB"), # rows
c("North", "South", "East"), # columns
c("2023", "2024") # layers
)
)
Accessing Array Elements
arr[1, 2, 3] # row 1, col 2, layer 3 arr[, , 1] # all of layer 1 (returns a matrix) arr[1, , ] # row 1 across all columns and layers arr["ProductA", "North", "2024"] # named access
Array Arithmetic
a1 <- array(1:8, dim = c(2, 2, 2)) a2 <- array(9:16, dim = c(2, 2, 2)) a1 + a2 # element-wise addition across all layers a1 * 2 # multiply every element by 2
Applying Functions Across Dimensions
# apply(array, margin, function) # margin: 1=rows, 2=columns, 3=layers, c(1,2)=each cell across layers apply(sales_arr, 3, sum) # total sales per year # 2023 2024 # 1180 1277 apply(sales_arr, 1, mean) # mean per product apply(sales_arr, 2, sum) # total per region
Practical: RGB Image Representation
A digital image is stored as a 3D array: height × width × 3 color channels (Red, Green, Blue).
# Tiny 3×3 pixel image with RGB channels image_data <- array( runif(27, 0, 255), # random pixel values dim = c(3, 3, 3) # 3 rows, 3 cols, 3 channels ) # Access the Red channel of all pixels image_data[, , 1] # Get one pixel's RGB values (row 2, col 2) image_data[2, 2, ]
Key Properties
dim(arr) # dimensions: rows, cols, layers length(arr) # total number of elements nrow(arr) # number of rows ncol(arr) # number of columns dimnames(arr) # names of each dimension
When to Use Arrays
Use an Array For: Alternative: ────────────────────────────────── ────────────────────────────── Time-series data per region/product Data frames with grouping columns Image or video data Lists of matrices 3D physics or simulation data Specialized packages (raster, etc.) Multi-way contingency tables table() function output
Arrays are less common in everyday data analysis than vectors, matrices, or data frames, but they are essential for spatial data, image analysis, and any problem with three or more dimensions of structure. Understanding arrays also helps you interpret multi-dimensional outputs from statistical functions.
