Create 3D array using the dim() function in R
Arrays in R Programming Language are the data objects which can store data in more than two dimensions. 3-D array is also known as a Multidimensional array. We can create a multidimensional array with dim() function.
Syntax:
dim=c(no_of_rows_ineach_array,no_of_columns_ineach_array,total_no_of arrays)
We can pass this dim as an argument to the array() function. This function is used to create an array.
array(data_inputs,dim=c(no of rows, no of cols, no of arrays)
Where data_inputs is the input data that includes list/vectors. We can pass these arguments(no of arrays, no of rows, no of cols) like a vector to the dim function. These will specify the total number of arrays. The second parameter will specify the no of rows in each array and the third parameter specify the no of columns in each array.
Steps –
- Create vectors
- Now pass the vectors to array() function
- Also, pass all the required parameters to this function with the correct values
- Display array
Example: R program to create an array with vectors of 3 dimensions(4 rows * r2 columns) each
R
# Create two vectors data1 <- c (1,2,3,4,5,6) data2 <- c (60, 18, 12, 13, 14, 19) # pass these vectors as input to the array. # 4 rows,2 columns and 3 arrays result <- array ( c (data1, data2), dim = c (4,2,3)) print (result) |
Output:
Example 2: two arrays with equal row and column size
R
# Create two vectors data1 <- c (1,2,3,4,5,6) data2 <- c (60, 18, 12, 13, 14, 19) # pass these vectors as input to the array. # 3 rows,3 columns and 2 arrays result <- array ( c (data1, data2), dim = c (3,3,2)) print (result) |
Output:
Example 3: Here we are using one more parameter (dimnames) and passing the values as a list to it.
- dimnames-Assigning names to each array, row, and column:
Syntax:
dimnames=list(row.names,column.names,matrix.names)
This can also be passed as an argument to an array.
R
# Create two vectors data1 <- c (1,2,3,4,5,6) data2 <- c (60, 18, 12, 13, 14, 19) # assigning row names row.names= c ( "row1" , "row2" , "row3" ) # assigning column names column.names= c ( "col1" , "col2" , "col3" ) # assigning array names matrix.names= c ( 'array1' , 'array2' , 'array3' ) # pass these vectors as input to the array. # 3 rows,3 columns and 3 arrays result <- array ( c (data1, data2), dim = c (3,3,3), dimnames= list (row.names,column.names, matrix.names)) print (result) |
Output:
Contact Us