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 x is an R object like a matrix, array, or data frame.
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 A for holding the result array. Here we are displaying a 3-dimensional array of 24 elements. Finally, print the array.
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
A= sample(1:5,24,replace = TRUE)
dim(A) = c(3,2,4)
print("3-dimension array is:")
print(A)
[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