Create a 3x3x2 Array in R using two Vectors
Write a R program to create an array with three columns, three rows, and two "tables", taking two vectors as input to the array. Print the array.
Sample Solution :
R Programming Code :
# Create a vector with elements 1, 3, 5, and 7
v1 = c(1, 3, 5, 7)
# Create a vector with elements 2, 4, 6, 8, and 10
v2 = c(2, 4, 6, 8, 10)
# Combine vectors v1 and v2 into a single array with dimensions 3x3x2
# The array will have 3 rows, 3 columns, and 2 "tables"
arra1 = array(c(v1, v2), dim = c(3, 3, 2))
# Print the content of the array
print(arra1)
Output:
, , 1 [,1] [,2] [,3] [1,] 1 7 6 [2,] 3 2 8 [3,] 5 4 10 , , 2 [,1] [,2] [,3] [1,] 1 7 6 [2,] 3 2 8 [3,] 5 4 10
Explanation:
- Create Vectors:
- v1 = c(1, 3, 5, 7): Creates a vector v1 with the values 1, 3, 5, and 7.
- v2 = c(2, 4, 6, 8, 10): Creates a vector v2 with the values 2, 4, 6, 8, and 10.
- Combine Vectors into an Array:
- array(c(v1, v2), dim = c(3, 3, 2)): Combines v1 and v2 into a single vector and reshapes it into a 3-dimensional array with dimensions 3x3x2.
- c(v1, v2): Concatenates v1 and v2 into one vector.
- dim = c(3, 3, 2): Specifies the dimensions of the array (3 rows, 3 columns, and 2 tables).
- Print the Array:
- print(arra1): Outputs the contents of the array to the console. The array will have two 3x3 matrices (tables), with each matrix filled with the concatenated values from v1 and v2.
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, passing in a vector of values and a vector of dimensions. Also provide names for each dimension.
Next: Write a R program to create a list of elements using vectors, matrices and a functions. Print the content of the list.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics