array() (Multi-dimensional Arrays)
In R, an array is a data structure for handling three-dimensional or higher-dimensional data. You create a multi-dimensional array with any number of dimensions using array(), inspect the dimensional structure with dim(), and access elements using the [,,] notation. While a matrix is a special case of a two-dimensional array, arrays are used for higher-dimensional data structures with three or more dimensions.
Syntax
# -----------------------------------------------
# array() — Create a multi-dimensional array
# -----------------------------------------------
array(data, dim = c(nrow, ncol, depth, ...))
# data : Vector of elements (filled column-major, from innermost dimension)
# dim : Size of each dimension specified with c()
# -----------------------------------------------
# Inspecting dimensions
# -----------------------------------------------
dim(a) # Returns an integer vector of each dimension's size
length(a) # Returns total number of elements (product of all dim sizes)
# -----------------------------------------------
# Setting dimension names
# -----------------------------------------------
dimnames(a) <- list(
c("row1", "row2"), # Names for 1st dimension (rows)
c("col1", "col2"), # Names for 2nd dimension (columns)
c("layer1", "layer2") # Names for 3rd dimension (layers)
)
# -----------------------------------------------
# Element access ([row, col, layer, ...])
# -----------------------------------------------
a[row, col, layer] # Access a single element by index (1-based)
a[1, , ] # All elements in row 1 (omit dimension)
a[, , 2] # Matrix slice where 3rd dimension == 2
a["row1", "col1", "layer1"] # Access by name (after setting dimnames)
# -----------------------------------------------
# Changing and inspecting dimensions
# -----------------------------------------------
dim(a) <- c(new_nrow, new_ncol, new_nlayer) # Change dimension by assigning to dim()
is.array(a) # Returns TRUE if object is an array
is.matrix(a) # Returns TRUE if object is a 2D matrix
apply(a, MARGIN, FUN) # Apply a function along a specified dimension
MARGIN Values for apply()
| MARGIN | Direction | Description |
|---|---|---|
1 | Row-wise | Apply function to each row. For 3D arrays, aggregate along the 1st dimension (rows). |
2 | Column-wise | Apply function to each column. For 3D arrays, aggregate along the 2nd dimension (columns). |
3 | Layer-wise | Apply function along the 3rd dimension (layers/slices) of a 3D array. |
c(1, 2) | Row × Column | Apply function to each row-column combination. Result is a matrix. |
c(1, 3) | Row × Layer | Apply function to each row-layer combination. |
Key Functions and Operators
| Function / Operator | Overview |
|---|---|
array(data, dim) | Returns an array by reshaping vector data into the shape specified by dim. Values are filled column-major (from the 1st dimension). |
dim(a) | Returns an integer vector of each dimension's size. Assigning to it changes the dimensions. |
dimnames(a) | Returns a list of names for each dimension. Assigning to it sets row names, column names, layer names, etc. |
length(a) | Returns the total number of elements. Equals the product of all dimension sizes in dim. |
is.array(a) | Returns a logical value indicating whether the object is an array. Matrices also return TRUE. |
is.matrix(a) | Returns a logical value indicating whether the object is a matrix (2D array). |
apply(a, MARGIN, FUN) | Applies function FUN along the specified dimension (MARGIN). Multiple dimensions can be specified. |
a[row, col, layer] | Access elements by index. Omitting a dimension (leaving blank) retrieves all elements along that dimension. |
which(a == value) | Returns linear indices of elements matching the condition. With arr.ind=TRUE, returns indices for each dimension. |
as.array(x) | Converts a vector or matrix to an array. The dim attribute is set. |
Sample Code
jujutsu_array_basic.R
# jujutsu_array_basic.R — Sample to explore array() basics
# Using Jujutsu Kaisen character data to demonstrate
# creating a 3D array, setting dimnames, element access, and aggregation with apply()
# -----------------------------------------------
# Creating a 3D array with array()
# -----------------------------------------------
# Jujutsu Kaisen characters (5 members)
members <- c("Itadori Yuji", "Fushiguro Megumi", "Kugisaki Nobara", "Gojo Satoru", "Nanami Kento")
# Evaluation categories (3 types)
categories <- c("Attack", "Cursed Energy Control", "Martial Arts")
# Evaluation periods (early/late)
terms <- c("Early", "Late")
# Scores for each character x category x period as a vector
# Order: 1st dimension (character) -> 2nd dimension (category) -> 3rd dimension (period)
scores <- c(
# --- Early (terms[1]) ---
# Attack: Itadori Fushiguro Kugisaki Gojo Nanami
85, 72, 78, 98, 88,
# Cursed Energy Control
60, 82, 70, 99, 91,
# Martial Arts
90, 75, 80, 95, 85,
# --- Late (terms[2]) ---
# Attack
92, 80, 85, 98, 89,
# Cursed Energy Control
75, 88, 78, 99, 93,
# Martial Arts
93, 80, 84, 96, 87
)
# Create a 3D array: 5 members x 3 categories x 2 periods
ability_arr <- array(scores, dim = c(5, 3, 2))
cat("=== Creating 3D Array ===\n")
cat("dim() :", dim(ability_arr), "\n") # 5 3 2
cat("length() :", length(ability_arr), "\n\n") # 30
# -----------------------------------------------
# Setting dimension names with dimnames()
# -----------------------------------------------
dimnames(ability_arr) <- list(
members, # 1st dimension (rows): character names
categories, # 2nd dimension (cols): evaluation categories
terms # 3rd dimension (layers): evaluation periods
)
cat("--- Checking dimnames() ---\n")
cat("1st dimension (members) :", dimnames(ability_arr)[[1]], "\n")
cat("2nd dimension (categories):", dimnames(ability_arr)[[2]], "\n")
cat("3rd dimension (terms) :", dimnames(ability_arr)[[3]], "\n\n")
# -----------------------------------------------
# Display each layer (slice)
# -----------------------------------------------
cat("=== Early Scores (ability_arr[, , 1]) ===\n")
print(ability_arr[, , 1])
cat("\n")
cat("=== Late Scores (ability_arr[, , \"Late\"]) ===\n")
print(ability_arr[, , "Late"])
cat("\n")
# -----------------------------------------------
# Element access (by index and by name)
# -----------------------------------------------
cat("--- Element Access ---\n")
# Access a specific element by index
cat("ability_arr[1, 1, 1] (Itadori, Early, Attack):", ability_arr[1, 1, 1], "\n")
# Access by name
cat("ability_arr[\"Gojo Satoru\", \"Cursed Energy Control\", \"Early\"]:",
ability_arr["Gojo Satoru", "Cursed Energy Control", "Early"], "\n")
# Extract all categories and periods for a specific character (returns a matrix)
cat("\nNanami Kento's all scores (ability_arr[\"Nanami Kento\", , ]):\n")
print(ability_arr["Nanami Kento", , ])
# Extract all characters and periods for a specific category
cat("\nAttack score list (ability_arr[, \"Attack\", ]):\n")
print(ability_arr[, "Attack", ])
cat("\n")
# -----------------------------------------------
# Aggregate per character using apply() (fix 1st dimension)
# -----------------------------------------------
cat("--- Aggregation with apply() ---\n")
# MARGIN=1: compute mean of all scores per character
member_avg <- apply(ability_arr, 1, mean)
cat("Average score per character:\n")
print(round(member_avg, 1))
cat("\n")
# MARGIN=2: compute mean across all characters and periods per category
cat_avg <- apply(ability_arr, 2, mean)
cat("Average score per category:\n")
print(round(cat_avg, 1))
cat("\n")
# MARGIN=3: compute mean of all scores per period
term_avg <- apply(ability_arr, 3, mean)
cat("Average score per period:\n")
print(round(term_avg, 1))
cat("\n")
# -----------------------------------------------
# MARGIN=c(1, 2): period mean per character x category
# -----------------------------------------------
cat("--- apply(MARGIN=c(1,2)): mean per character x category ---\n")
cross_avg <- apply(ability_arr, c(1, 2), mean)
cat("Mean score per character x category:\n")
print(round(cross_avg, 1))
cat("\n")
# -----------------------------------------------
# MARGIN=c(1, 3): total score per character x period
# -----------------------------------------------
cat("--- apply(MARGIN=c(1,3)): total score per character x period ---\n")
member_term_total <- apply(ability_arr, c(1, 3), sum)
cat("Total score per character x period:\n")
print(member_term_total)
cat("\n")
# Calculate growth from Early to Late
growth <- member_term_total[, "Late"] - member_term_total[, "Early"]
cat("Score growth (Early -> Late):\n")
print(growth)
cat("\n")
top_growth <- names(which.max(growth))
cat("Most improved character:", top_growth,
"(+", max(growth), "points)\n\n")
# -----------------------------------------------
# Reshaping dimensions with dim()
# -----------------------------------------------
cat("--- Reshaping dimensions with dim() ---\n")
# Convert Early data to a 1D vector
score_vec <- as.vector(ability_arr[, , 1])
cat("Length after as.vector():", length(score_vec), "\n")
# Reshape to 3x5 by assigning to dim()
dim(score_vec) <- c(3, 5)
rownames(score_vec) <- categories
colnames(score_vec) <- members
cat("Early scores reshaped to 3x5:\n")
print(score_vec)
cat("\n")
# -----------------------------------------------
# Search for elements with which()
# -----------------------------------------------
cat("--- Searching for high-score elements with which() ---\n")
# With arr.ind=TRUE, returns indices for each dimension
high_idx <- which(ability_arr >= 95, arr.ind = TRUE)
cat("Elements with score >= 95 (indices per dimension):\n")
for (i in seq_len(nrow(high_idx))) {
r <- high_idx[i, 1] # 1st dimension (character) index
c <- high_idx[i, 2] # 2nd dimension (category) index
l <- high_idx[i, 3] # 3rd dimension (period) index
cat(sprintf(" %-20s | %-25s | %s : %d\n",
members[r], categories[c], terms[l], ability_arr[r, c, l]))
}
Rscript jujutsu_array_basic.R
=== Creating 3D Array ===
dim() : 5 3 2
length() : 30
--- Checking dimnames() ---
1st dimension (members) : Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru Nanami Kento
2nd dimension (categories): Attack Cursed Energy Control Martial Arts
3rd dimension (terms) : Early Late
=== Early Scores (ability_arr[, , 1]) ===
Attack Cursed Energy Control Martial Arts
Itadori Yuji 85 60 90
Fushiguro Megumi 72 82 75
Kugisaki Nobara 78 70 80
Gojo Satoru 98 99 95
Nanami Kento 88 91 85
=== Late Scores (ability_arr[, , "Late"]) ===
Attack Cursed Energy Control Martial Arts
Itadori Yuji 92 75 93
Fushiguro Megumi 80 88 80
Kugisaki Nobara 85 78 84
Gojo Satoru 98 99 96
Nanami Kento 89 93 87
--- Element Access ---
ability_arr[1, 1, 1] (Itadori, Early, Attack): 85
ability_arr["Gojo Satoru", "Cursed Energy Control", "Early"]: 99
Nanami Kento's all scores (ability_arr["Nanami Kento", , ]):
Early Late
Attack 88 89
Cursed Energy Control 91 93
Martial Arts 85 87
Attack score list (ability_arr[, "Attack", ]):
Early Late
Itadori Yuji 85 92
Fushiguro Megumi 72 80
Kugisaki Nobara 78 85
Gojo Satoru 98 98
Nanami Kento 88 89
--- Aggregation with apply() ---
Average score per character:
Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru Nanami Kento
82.5 79.5 79.2 97.5 88.8
Average score per category:
Attack Cursed Energy Control Martial Arts
85.7 83.2 85.2
Average score per period:
Early Late
82.9 87.3
--- apply(MARGIN=c(1,2)): mean per character x category ---
Mean score per character x category:
Attack Cursed Energy Control Martial Arts
Itadori Yuji 88.5 67.5 91.5
Fushiguro Megumi 76.0 85.0 77.5
Kugisaki Nobara 81.5 74.0 82.0
Gojo Satoru 98.0 99.0 95.5
Nanami Kento 88.5 92.0 86.0
--- apply(MARGIN=c(1,3)): total score per character x period ---
Total score per character x period:
Early Late
Itadori Yuji 235 260
Fushiguro Megumi 229 248
Kugisaki Nobara 228 247
Gojo Satoru 292 293
Nanami Kento 264 269
Score growth (Early -> Late):
Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru Nanami Kento
25 19 19 1 5
Most improved character: Itadori Yuji (+ 25 points)
--- Reshaping dimensions with dim() ---
Length after as.vector(): 15
Early scores reshaped to 3x5:
Itadori Yuji Fushiguro Megumi Kugisaki Nobara Gojo Satoru Nanami Kento
Attack 85 98 82 91 80
Cursed Energy Control 60 80 85 72 99
Martial Arts 90 75 80 95 85
--- Searching for high-score elements with which() ---
Elements with score >= 95 (indices per dimension):
Gojo Satoru | Attack | Early : 98
Gojo Satoru | Cursed Energy Control | Early : 99
Gojo Satoru | Martial Arts | Early : 95
Gojo Satoru | Attack | Late : 98
Gojo Satoru | Cursed Energy Control | Late : 99
Gojo Satoru | Martial Arts | Late : 96
Summary
In R, arrays are created with array(data, dim = c(...)) to produce multi-dimensional data structures with any number of dimensions. A matrix is a special case of a two-dimensional array and also returns TRUE for is.array(). Dimension names are set via dimnames() as a list, enabling named access like a["row", "col", "layer"]. Elements are accessed with the [row, col, layer] notation, and omitting a dimension (leaving it blank) retrieves all elements along that dimension. The MARGIN argument of apply() accepts dimension indices to perform flexible aggregation along specific dimensions. You can change the shape of the same data by directly assigning to dim(), and which(..., arr.ind=TRUE) retrieves the per-dimension indices of all elements matching a condition at once. For two-dimensional data operations, see Matrix Basics; for tabular data, see data.frame Basics.
Common Mistakes
dim does not match the number of elements
When the product of the dimensions specified in the dim argument of array() does not match the number of elements passed to data, R automatically repeats (recycles) the data to fill the array. This can cause unintended repetition.
array_dim_mismatch.R
# Data with 2 elements specified with dim=c(3,3) (2 and 9 do not match) a <- array(1:2, dim = c(3, 3)) print(a)
[,1] [,2] [,3]
[1,] 1 2 1
[2,] 2 1 2
[3,] 1 2 1
Always verify that the data is filled as intended.
Confusing matrix and array
A matrix is a special case of a two-dimensional array. array(data, dim=c(3,3)) and matrix(data, 3, 3) produce the same result, but for three or more dimensions, use array.
array_vs_matrix.R
# Comparing matrix and array
m <- matrix(1:9, nrow = 3, ncol = 3)
a <- array(1:9, dim = c(3, 3))
cat("is.matrix(m):", is.matrix(m), "\n")
cat("is.matrix(a):", is.matrix(a), "\n")
cat("is.array(m):", is.array(m), "\n")
cat("is.array(a):", is.array(a), "\n")
is.matrix(m): TRUE is.matrix(a): TRUE is.array(m): TRUE is.array(a): TRUE
A matrix is a type of array. Use array when handling data with three or more dimensions.
Dimension is dropped by vectorized operations
Applying operations to an array may not preserve dimension information. Using apply() allows operations that retain dimension structure.
array_dim_drop.R
power <- array(c(9001, 7500, 8200, 6000), dim = c(2, 2))
# Column-wise mean
col_means <- apply(power, 2, mean)
print(col_means)
cat("class:", class(col_means), "\n")
[1] 8250.5 7100.0 class: numeric
The result of apply() becomes a vector or matrix. Keep in mind that dimensions may change and write code accordingly.
If you find any errors or copyright issues, please contact us.