R language Arrays
1 arrays are r Data Objects that can store data in more than two dimensions
How to create
Create an array using the array () function. it uses vectors as input and creates an array using the values in the Dim parameter.
Cases
The following example creates an array of two 3x3 matrices, each with 3 rows and 3 columns.
# Create vectors of different lengths.
Vector1 <-C(5, 9, 3)
Vector2 <-C (all, one, one, ten, +)
# take these vectors as input to the array.
Result <-Array(c(Vector1, Vector2), Dim = C(3, 3, 2)) // This is how to create, Dim(A few lines, Several columns, number of matrices)
Print(Result)
When we execute the above code, it produces the following result --
, , 1
[, 1] [, 2] [, 3]
[1,] 5
[2,] 9
[3,] 3
, , 2
[, 1] [, 2] [, 3]
[1,] 5
[2,] 9
[3,] 3
2 naming columns and rows
We can use the dimnames parameter to name the rows, columns, and matrices in the array.
Column.names <-C("COL1", "COL2", "COL3")
Row.names <-C("ROW1", "ROW2", "ROW3")
Matrix.names <-C("Matrix1", "Matrix2")
Result <-Array(c(Vector1, Vector2), Dim = C(3, 3, 2), dimnames = List(row.names , Column.names, Matrix.names))// this side name line
When we execute the above code, it produces the following result --
, , Matrix1
COL1 COL2 COL3
ROW1 5
ROW2 9
ROW3 3
, , Matrix2
COL1 COL2 COL3
ROW1 5
ROW2 9
ROW3 3
3 Accessing array elements
# Print The third row of the second matrix of the array.
Print(Result[3, 2]) // 2nd Matrix 3rd line
# Print The element in the 1st row and 3rd column of the 1st matrix.
Print(Result[1, 3, 1])// 1th Matrix 1th column 3rd line
# Print the 2nd Matrix.
Print(Result[,, 2])// 2nd Matrix
4 manipulating array elements
Because arrays are composed of multidimensional matrices, the operation of an array element is performed by accessing the elements of the matrix.
# Create vectors of different lengths.
Vector1 <-C(5, 9, 3)
Vector2 <-C (all, one, one, ten, +)
# take these vectors as input to the array.
Array1 <-Array(c(Vector1, Vector2), Dim = C(3, 3, 2))
# Create vectors of different lengths.
Array2 <-Array(c(Vector1, Vector2), Dim = C(3, 3, 2))
# create Matrices from these arrays.
matrix1 <-array1[,, 2] // 2nd Matrix obtained
matrix2 <-array2[,, 2]// get 2nd matrix
# ADD the matrices.
Result <-matrix1+matrix2// matrix addition
Print(Result)
R Type 4R language array