Create a Matrix from a List of given Vectors in R Programming
Write a R program to create a matrix from a list of given vectors.
Sample Solution:
R Programming Code:
# Initialize an empty list
l = list()
# Loop through numbers 1 to 5
for (i in 1:5)
# Assign a vector to each list element, where the vector consists of the loop index followed by numbers 1 to 4
l[[i]] <- c(i, 1:4)
# Print a message indicating the list of vectors
print("List of vectors:")
# Print the list of vectors
print(l)
# Combine the list of vectors into a matrix by row-binding them
result = do.call(rbind, l)
# Print a message indicating the new matrix
print("New Matrix:")
# Print the resulting matrix
print(result)
Output:
[1] "List of vectors:" [[1]] [1] 1 1 2 3 4 [[2]] [1] 2 1 2 3 4 [[3]] [1] 3 1 2 3 4 [[4]] [1] 4 1 2 3 4 [[5]] [1] 5 1 2 3 4 [1] "New Matrix:" [,1] [,2] [,3] [,4] [,5] [1,] 1 1 2 3 4 [2,] 2 1 2 3 4 [3,] 3 1 2 3 4 [4,] 4 1 2 3 4 [5,] 5 1 2 3 4
Explanation:
- Initialize an empty list with l = list(), which will be used to store vectors.
- Loop through numbers 1 to 5: For each number i in the range from 1 to 5, create a vector c(i, 1:4) where i is the current number and 1:4 is a sequence of numbers from 1 to 4. Store each vector in the list l at position i.
- Print a message indicating that the list of vectors will be displayed.
- Print the list of vectors to show the content of the list l, which contains vectors created in the loop.
- Combine the list into a matrix: Use do.call(rbind, l) to row-bind the vectors in the list l into a single matrix and assign it to result.
- Print a message indicating that the new matrix will be displayed.
- Print the resulting matrix to show the matrix result created by row-binding the vectors from the list l.
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 two 2x3 matrix and add, subtract, multiply and divide the matrixes.
Next: Write a R program to extract the submatrix whose rows have column value > 7 from a given matrix.
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