R Tutorial



R ARRAYS


Arrays in R

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.

Creating an Array

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
  

Understanding Dimensions

  • dim = c(rows, columns, layers)
  • In the above example, we have 2 layers, each with 3 rows and 3 columns

Accessing Array Elements

  • arr[1, 2, 1] → 1st row, 2nd column, 1st layer
  • arr[ , , 1] → entire first 2D matrix (1st layer)
  • arr[2, , 2] → 2nd row of the 2nd layer

Naming Dimensions

You 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"]

Array Operations

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
  

Useful Functions

  • dim(arr) – get dimensions
  • length(arr) – total number of elements
  • apply(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
  

Summary

  • Arrays are useful for handling data in 3 or more dimensions.
  • Created using array() with the dim parameter.
  • Access elements using [row, col, layer] syntax.
  • Supports vectorized operations and apply().

Practice Exercises

  • Create a 3x3x2 array and fill with numbers 1 to 18.
  • Name all dimensions and access a specific element using names.
  • Find the sum of all elements in the second layer.
  • Use apply() to find column sums across all layers.
  • Create two arrays and perform addition and multiplication.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review