Array in R

In R, Arrays are the data types can store data in more than two dimensions. An array can be created using the array() function. It takes vectors as input and uses the values in the dim parameter to create an array. If you create an array of dimension (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. Arrays can store only data type. 

 

# Create two vectors of different lengths.
v1 <- c(1,2,3)
v2 <- 100:110
# Take these vectors as input to create an array.
arr1 <- array(c(v1,v2))
arr1
arr2 <- array(c(v1,v2), dim=c(2,7))
arr2

Output:

> arr1
[1] 1 2 3 100 101 102 103 104 105 106 107 108 109 110
> arr2 <- array(c(v1,v2), dim=c(2,7))
> arr2
[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 3 101 103 105 107 109
[2,] 2 100 102 104 106 108 110

The following example will create an array of two 2×7 matrices each with 2 rows and 7 columns.

 

arr3 <- array(c(v1,v2), dim=c(2,7,2))
arr3

Output:

> arr3
, , 1

[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 3 101 103 105 107 109
[2,] 2 100 102 104 106 108 110

, , 2

[,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,] 1 3 101 103 105 107 109
[2,] 2 100 102 104 106 108 110

Give a Name to Columns and Rows:

You can give names to the rows, columns and matrices in the array by setting the dimnames parameter.


v1 <- c(1,2,3)
v2 <- 100:110
col.names <- c("Col1","Col2","Col3","Col4","Col5","Col6","Col7")
row.names <- c("Row1","Row2")
matrix.names <- c("Matrix1","Matrix2")
arr4 <- array(c(v1,v2), dim=c(2,7,2), dimnames = list(row.names,col.names, matrix.names))

arr4

Output:

, , Matrix1

Col1 Col2 Col3 Col4 Col5 Col6 Col7
Row1 1 3 101 103 105 107 109
Row2 2 100 102 104 106 108 110

, , Matrix2

Col1 Col2 Col3 Col4 Col5 Col6 Col7
Row1 1 3 101 103 105 107 109
Row2 2 100 102 104 106 108 110

Accessing/Extracting Array Elements:

 

# Print the 2nd row of the 1st matrix of the array.
print(arr4[2,,1])

# Print the element in the 2nd row and 4th column of the 2nd matrix.
print(arr4[2,4,2])

# Print the 2nd Matrix.
print(arr4[,,2])

Output:

> print(arr4[2,,1])
Col1 Col2 Col3 Col4 Col5 Col6 Col7
2 100 102 104 106 108 110
>
> # Print the element in the 2nd row and 4th column of the 2nd matrix.
> print(arr4[2,4,2])
[1] 104
>
> # Print the 2nd Matrix.
> print(arr4[,,2])
Col1 Col2 Col3 Col4 Col5 Col6 Col7
Row1 1 3 101 103 105 107 109
Row2 2 100 102 104 106 108 110

Matrices

Data Frames