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
– 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.
A = sample(1:5,24,replace = TRUE)
dim(A) = c(3,2,4)
print("3-dimension array is:")
## [1] "3-dimension array is:"
print(A)
## , , 1
##
## [,1] [,2]
## [1,] 1 5
## [2,] 5 2
## [3,] 1 4
##
## , , 2
##
## [,1] [,2]
## [1,] 5 1
## [2,] 3 5
## [3,] 3 4
##
## , , 3
##
## [,1] [,2]
## [1,] 1 2
## [2,] 4 2
## [3,] 2 1
##
## , , 4
##
## [,1] [,2]
## [1,] 2 2
## [2,] 3 3
## [3,] 3 1
B = sample(1:5, 12,replace = TRUE)
dim(B) = c(3,2,2)
print("3-dimension array is:")
## [1] "3-dimension array is:"
print(B)
## , , 1
##
## [,1] [,2]
## [1,] 1 2
## [2,] 3 5
## [3,] 3 5
##
## , , 2
##
## [,1] [,2]
## [1,] 4 2
## [2,] 4 2
## [3,] 2 3