w3resource

Create a 3D Array of 24 Elements using the dim() Function in R

R Programming: Array Exercise-3 with Solution

Write a R program to create an 3 dimensional array of 24 elements using the dim() function.

Sample Solution :

R Programming Code :

# Generate a vector 'v' with 24 random integers between 1 and 5, allowing replacement
v = sample(1:5, 24, replace = TRUE)

# Reshape the vector 'v' into a 3-dimensional array with dimensions 3x2x4
dim(v) = c(3, 2, 4)

# Print a message indicating the output is a 3-dimensional array
print("3-dimension array:")

# Display the contents of the 3-dimensional array
print(v)

Output:

[1] "3-dimension array:"
, , 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                         

Explanation:

  • Generate Random Numbers: Creates a vector v with 24 random integers sampled from 1 to 5, with replacement allowed.
  • Set Dimensions: Reshapes the vector v into a 3-dimensional array with dimensions 3x2x4.
  • Print Message: Displays a message indicating that the following output is a 3-dimensional array.
  • Print Array: Outputs the contents of the 3-dimensional array v.

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to create an array of two 3x3 matrices each with 3 rows and 3 columns from two given two vectors.
Next: Write a R program to create an array of two 3x3 matrices each with 3 rows and 3 columns from two given two vectors. Print the second row of the second matrix of the array and the element in the 3rd row and 3rd column of the 1st matrix.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/r-programming-exercises/array/r-programming-array-exercise-3.php