Multidimensional Array in R

Multidimensional Array in detail

Arrays in R are data objects that store data in more than two dimensions. For example, if we create an array of dimensions (2, 3, 4), it forms 4 rectangular matrices, each containing 2 rows and 3 columns. These types of arrays are called Multidimensional Arrays.

Creating a Multidimensional Array

An array is created using the array() function. It takes vectors as input and uses the values in the dim parameter to define the number of dimensions.

Syntax:

grep(pattern, text_vector, ignore.case=FALSE)MArray = array(c(vec1, vec2), dim)

Example:

# Create two vectors
vector1 <- c(2, 4, 6)
vector2 <- c(8, 10, 12, 14, 16, 18)

# Create an array from these vectors
result <- array(c(vector1, vector2), dim = c(3, 3, 2))

# Print the array
print(result)

Output:

, , 1

     [,1] [,2] [,3]
[1,]    2    8   14
[2,]    4   10   16
[3,]    6   12   18

, , 2

     [,1] [,2] [,3]
[1,]    2    8   14
[2,]    4   10   16
[3,]    6   12   18
Naming Columns and Rows

We can assign names to rows, columns, and matrices in the array using the dimnames parameter.

Example:

# Create two vectors
vector1 <- c(2, 4, 6)
vector2 <- c(8, 10, 12, 14, 16, 18)

# Define names for rows, columns, and matrices
column.names <- c("Col_A", "Col_B", "Col_C")
row.names <- c("Row_1", "Row_2", "Row_3")
matrix.names <- c("Matrix_A", "Matrix_B")

# Create an array with names
result <- array(c(vector1, vector2), dim = c(3, 3, 2),
                dimnames = list(row.names, column.names, matrix.names))

# Print the array
print(result)

Output:

, , Matrix_A

       Col_A Col_B Col_C
Row_1     2     8    14
Row_2     4    10    16
Row_3     6    12    18

, , Matrix_B

       Col_A Col_B Col_C
Row_1     2     8    14
Row_2     4    10    16
Row_3     6    12    18
Manipulating Array Elements

Since arrays consist of matrices in multiple dimensions, operations can be performed by accessing individual matrix elements.

Example:

# Create first array
vector1 <- c(2, 4, 6)
vector2 <- c(8, 10, 12, 14, 16, 18)
array1 <- array(c(vector1, vector2), dim = c(3, 3, 2))

# Create second array
vector3 <- c(1, 3, 5)
vector4 <- c(7, 9, 11, 13, 15, 17)
array2 <- array(c(vector3, vector4), dim = c(3, 3, 2))

# Extract second matrices from both arrays
matrix1 <- array1[,,2]
matrix2 <- array2[,,2]

# Add the matrices
result <- matrix1 + matrix2
print(result)

Output:

[,1] [,2] [,3]
[1,]    9   21   27
[2,]   17   25   31
[3,]   23   33   35

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *