R Program to create an 3 dimensional array of 24 elements using the dim() function


April 9, 2022, Learn eTutorial
1673

How to create a 3-dimensional array of 24 elements using the dim() function

Here we are explaining how to write an R program to create a 3-dimensional array of 24 elements using the dim() function. Here we are using a built-in function dim() for this. This function helps to retrieve or set the dimension of an object. The syntax of this function is 

dim(x) 

Where is an R object like a matrix, array, or data frame. 

How to create a 3-dimensional array using the dim() function using the R program

Below are the steps used in the R program to create a 3-dimensional array of 24 elements using the dim() function. In this R program, we directly give the values to a dim(). Here we are using variable for holding the result array. Here we are displaying a 3-dimensional array of 24 elements. Finally, print the array.

ALGORITHM

STEP 1: Assign array elements into the variable A

STEP 2: The 3-dimensional array is created by using dim()

STEP 3:limit the number of elements to 24

STEP 4: Print the 3-dimensional array

R Source Code

                                          A=  sample(1:5,24,replace = TRUE)
dim(A) = c(3,2,4)
print("3-dimension array is:")
print(A)
                                      

OUTPUT

[1] "3-dimension array is:"
, , 1

     [,1] [,2]
[1,]    4    2
[2,]    4    2
[3,]    2    1

, , 2

     [,1] [,2]
[1,]    4    2
[2,]    2    4
[3,]    2    4

, , 3

     [,1] [,2]
[1,]    4    2
[2,]    1    5
[3,]    3    2

, , 4

     [,1] [,2]
[1,]    3    3
[2,]    1    5
[3,]    1    2