An array in R is a multi-dimensional data structure that can store data in more than two dimensions. While matrices are limited to 2D (rows and columns), arrays can be 3D, 4D, and beyond.
Use the array()
function:
# Create a 3D array with 2 matrices, each 3x3 arr <- array(1:18, dim = c(3, 3, 2)) # This creates 2 matrices (3x3), one after another
dim = c(rows, columns, layers)
arr[1, 2, 1]
→ 1st row, 2nd column, 1st layerarr[ , , 1]
→ entire first 2D matrix (1st layer)arr[2, , 2]
→ 2nd row of the 2nd layerYou can name rows, columns, and layers (matrix names):
arr <- array(1:8, dim = c(2, 2, 2), dimnames = list( c("Row1", "Row2"), c("Col1", "Col2"), c("Matrix1", "Matrix2") ))
Now access using names: arr["Row1", "Col2", "Matrix1"]
You can perform operations on arrays like you do with vectors and matrices:
# Add two arrays arr1 <- array(1:8, dim = c(2, 2, 2)) arr2 <- array(9:16, dim = c(2, 2, 2)) result <- arr1 + arr2
dim(arr)
– get dimensionslength(arr)
– total number of elementsapply(arr, margin, FUN)
– apply function across array dimensions
Example using apply()
:
# Sum of rows (1 = row, 2 = column, 3 = layer) apply(arr, 1, sum) # Sum across rows apply(arr, 2, sum) # Sum across columns
array()
with the dim
parameter.[row, col, layer]
syntax.apply()
.apply()
to find column sums across all layers.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!