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

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 x 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 A 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:")
## [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

R Source Code

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