R Arrays
In R, arrays are the data objects which allow us to store data in more than two dimensions. In R, an array is created with the help of the array() function. This array() function takes a vector as an input and to create an array it uses vectors values in the dim parameter.
For example - if we will create an array of dimension (2, 3, 4) then it will create 4 rectangular matrices of 2 row and 3 columns.
R Array Syntax
There is the following syntax of R arrays:
array_name ← array(data, dim= (row_size, column_size, matrices, dim_names))
data
The data is the first argument in the array() function. It is an input vector which is given to the array.
matrices
In R, the array consists of multi-dimensional matrices.
row_size
This parameter defines the number of row elements which an array can store.
column_size
This parameter defines the number of columns elements which an array can store.
dim_names
This parameter is used to change the default names of rows and columns.
How to create?
In R, array creation is quite simple. We can easily create an array using vector and array() function. In array, data is stored in the form of the matrix. There are only two steps to create a matrix which are as follows
- In the first step, we will create two vectors of different lengths.
- Once our vectors are created, we take these vectors as inputs to the array.
Let see an example to understand how we can implement an array with the help of the vectors and array() function.
Example
#Creating two vectors of different lengths vec1 <-c(1,3,5) vec2 <-c(10,11,12,13,14,15) #Taking these vectors as input to the array res <- array(c(vec1,vec2),dim=c(3,3,2)) print(res)
Output
, , 1 [,1] [,2] [,3] [1,] 1 10 13 [2,] 3 11 14 [3,] 5 12 15 , , 2 [,1] [,2] [,3] [1,] 1 10 13 [2,] 3 11 14 [3,] 5 12 15
Naming rows and columns
In R, we can give the names to the rows, columns, and matrices of the array. This is done with the help of the dim name parameter of the array() function.
It is not necessary to give the name to the rows and columns. It is only used to differentiate the row and column for better understanding.
Below is an example, in which we create two arrays and giving names to the rows, columns, and matrices.
Example
#Creating two vectors of different lengths vec1 <-c(1,3,5) vec2 <-c(10,11,12,13,14,15) #Initializing names for rows, columns and matrices col_names <- c("Col1","Col2","Col3") row_names <- c("Row1","Row2","Row3") matrix_names <- c("Matrix1","Matrix2") #Taking the vectors as input to the array res <- array(c(vec1,vec2),dim=c(3,3,2),dimnames=list(row_names,col_names,matrix_names)) print(res)
Output
, , Matrix1 Col1 Col2 Col3 Row1 1 10 13 Row2 3 11 14 Row3 5 12 15 , , Matrix2 Col1 Col2 Col3 Row1 1 10 13 Row2 3 11 14 Row3 5 12 15