Arrays in R

📘 Introduction

An array is a multi-dimensional data structure in R that stores elements of the same data type. While a matrix is limited to two dimensions (rows and columns), an array can have two or more dimensions, making it suitable for storing complex datasets such as images, scientific measurements, simulation results, and multidimensional observations.

Information

A matrix is a special case of an array with exactly two dimensions. Arrays can have any number of dimensions.

đŸŽ¯ Why Use Arrays?

  • Store data in multiple dimensions.
  • Represent complex datasets efficiently.
  • Perform scientific and statistical computations.
  • Store image and simulation data.
  • Organize related information across several dimensions.

đŸ“Ļ Creating an Array

The array() function is used to create arrays in R. The dim argument specifies the size of each dimension.

Creating a 3-Dimensional Array

arr <- array(1:24, dim = c(3, 4, 2))

print(arr)

Understanding the Dimensions

In the above example, dim = c(3, 4, 2) creates an array with:

  • 3 rows
  • 4 columns
  • 2 matrices (layers)

🧩 Structure of an Array

Array
Dimension 1 (Rows)
Dimension 2 (Columns)
Dimension 3 (Layers)
Matrix 1
Matrix 2

🏷 Naming Dimensions

Dimension names improve readability by assigning meaningful labels to rows, columns, and layers.

Named Array

arr <- array(
  1:12,
  dim = c(2, 3, 2),
  dimnames = list(
    c("Row1", "Row2"),
    c("Col1", "Col2", "Col3"),
    c("Layer1", "Layer2")
  )
)

print(arr)

📏 Array Dimensions

FunctionDescriptionExample
dim()Returns the dimensions of the array.dim(arr)
length()Returns the total number of elements.length(arr)
dimnames()Returns the dimension names.dimnames(arr)

Checking Array Properties

arr <- array(1:24, dim = c(3,4,2))

print(dim(arr))
print(length(arr))

đŸŽ¯ Accessing Array Elements

Array elements are accessed using indexes for each dimension. The syntax is array[row, column, layer].

Accessing Elements

arr <- array(1:24, dim = c(3,4,2))

print(arr[2,3,1])
print(arr[1,,1])
print(arr[,2,2])

âœī¸ Modifying Array Elements

Updating an Element

arr <- array(1:8, dim = c(2,2,2))

arr[1,2,1] <- 100

print(arr)

📊 Creating Arrays from Vectors

Arrays are commonly created by arranging vector elements into multiple dimensions.

Array from a Vector

values <- c(10,20,30,40,50,60,70,80)

arr <- array(values, dim = c(2,2,2))

print(arr)

➕ Arithmetic Operations on Arrays

Arrays of the same dimensions support element-wise arithmetic operations.

Array Arithmetic

A <- array(1:8, dim = c(2,2,2))
B <- array(9:16, dim = c(2,2,2))

print(A + B)
print(A - B)
print(A * B)
print(A / B)

🧮 Useful Array Functions

FunctionDescription
apply()Applies a function across selected dimensions.
dim()Returns array dimensions.
length()Returns the total number of elements.
dimnames()Returns or sets dimension names.

Using apply()

arr <- array(1:24, dim = c(3,4,2))

# Sum of each row
apply(arr, 1, sum)

# Sum of each column
apply(arr, 2, sum)

# Sum of each layer
apply(arr, 3, sum)

🔍 Selecting Entire Dimensions

Selecting Rows, Columns, and Layers

arr <- array(1:24, dim = c(3,4,2))

# First row of first layer
print(arr[1,,1])

# Second column of second layer
print(arr[,2,2])

# Entire first layer
print(arr[,,1])

🧭 Array Workflow

Create an Array
Define Dimensions
Store Data
Access Elements
Modify Values
Perform Calculations

🌍 Real-World Example

Suppose a company records quarterly sales for three products across two years.

Quarterly Sales Data

sales <- array(
  c(
    120,150,180,
    140,170,190,
    160,180,210,
    170,190,220,
    180,210,230,
    190,220,240,
    200,230,250,
    210,240,260
  ),
  dim = c(4,3,2),
  dimnames = list(
    c("Q1","Q2","Q3","Q4"),
    c("Product A","Product B","Product C"),
    c("2025","2026")
  )
)

print(sales)
apply(sales, 3, sum)

📋 Matrix vs Array

FeatureMatrixArray
DimensionsTwoTwo or more
Rows and ColumnsYesYes (plus additional dimensions)
Data TypeSingle typeSingle type
ApplicationsTabular dataMultidimensional data

âš ī¸ Common Mistakes

MistakeExplanationSolution
Incorrect dimensionsThe number of elements must match the specified dimensions.Ensure that the product of all dimensions equals the number of elements.
Using the wrong number of indexesEach dimension requires its own index.Provide an index for every dimension when accessing elements.
Mixing data typesArrays contain only one data type.Store homogeneous data or use a list for mixed data.
Ignoring dimension orderIncorrect indexing may retrieve unexpected values.Check the array dimensions using dim() before indexing.

💡 Best Practices

  • Use arrays for multidimensional datasets.
  • Assign meaningful dimension names for better readability.
  • Verify dimensions using dim() before processing data.
  • Use apply() to perform calculations efficiently across dimensions.
  • Choose arrays only when all elements are of the same data type.

Best Practice

Arrays are ideal for organizing multidimensional numerical data. Properly naming dimensions and using built-in functions such as apply() can greatly simplify data analysis and improve code readability.

📝 Summary

Arrays are multidimensional data structures in R that store elements of the same data type across two or more dimensions. You learned how to create arrays, define dimensions, assign names, access and modify elements, perform arithmetic operations, and use functions such as apply() for efficient data processing. Arrays are widely used in statistics, machine learning, image processing, and scientific computing where multidimensional data needs to be stored and analyzed.

>>"Arrays extend the power of matrices by enabling efficient organization and analysis of multidimensional data."