In this tutorial you will learn about the R Arrays and its application with practical example.
R Arrays
Array is a data structure that enable you to store multi dimensional(more than 2 dimensions) data of same type. In R, an array of (2, 3, 2) dimension contains 2 matrix of 2×3.
Creating Arrays
In R, an array can be created using the array() function as following –
Syntax:-
1 |
array(data, dim) |
Above is the general syntax of array() function, here
data:- It is a vector input used to create array.
dim:- It is used to represent array dimensions.
Example:-
1 2 3 4 5 6 7 |
print("W3Adda - R Arrays") # Two vectors of different lengths. a <- c(1,2,3) b <- c(10,11,12,13,14,15) # Take vectors as input and creats array. arr <- array(c(a,b),dim = c(3,3,2)) print(arr) |
Output:-
Naming Columns and Rows
The dimnames parameter in array() function is used to give names to the rows, columns along with matrices.
Example:-
1 2 3 4 5 6 7 8 9 |
print("W3Adda - R Naming Arrays") # Two vectors of different lengths. a <- c(1,2,3) b <- c(10,11,12,13,14,15) column.names <- c ("COLA","COLB","COLC") row.names <- c ("ROWA","ROWB","ROWC") matrix.names <- c ("MatA", "MatB") arr <- array (c (a,b), dim=c (3,3,2), dimnames=list (column.names, row.names, matrix.names)) print(arr) |
Output:-
Accessing Array Elements
Array elements can be accessed by using the row and column index of the element as following –
Syntax:-
1 |
arr[row,col,matrix] |
arr:- Array name
row:- row index of the element, if not provided specified row elements will be fetched for all columns.
col:- column index of the element, if not provided specified column elements will be fetched for all rows.
matrix:- matrix index.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
print("W3Adda - R Accessing Array Elements") # Two vectors of different lengths. a <- c(1,2,3) b <- c(10,11,12,13,14,15) column.names <- c ("COLA","COLB","COLC") row.names <- c ("ROWA","ROWB","ROWC") matrix.names <- c ("MatA", "MatB") arr <- array (c (a,b), dim=c (3,3,2), dimnames=list (column.names, row.names, matrix.names)) print(arr) # Print the third row of the second matrix of the array. print(arr[3,,2]) # Print the element in the 1st row and 3rd column of the 1st matrix. print(arr[1,3,1]) # Print the 2nd Matrix. print(arr[,,2]) |
When we run the above R script, we see the following output –
Output:-