Write a R program to create a matrix from a list of given vectors

1. Introduction

This R program demonstrates how to create a matrix from a list of given vectors. Each vector in the list will constitute a row in the resulting matrix.

2. Program Steps

1. Create a list of vectors.

2. Convert the list of vectors into a matrix.

3. Print the resulting matrix.

3. Code Program

# Step 1: Create a list of vectors
vectors_list <- list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9))

# Step 2: Convert the list of vectors into a matrix
matrix_from_list <- do.call(rbind, vectors_list)

# Step 3: Print the matrix
print("Matrix created from list of vectors:")
print(matrix_from_list)

Output:

Matrix created from list of vectors:
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

Explanation:

1. list(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9)): Initializes a list containing three vectors.

2. do.call(rbind, vectors_list): Converts the list of vectors into a matrix. The rbind function binds the vectors row-wise.

3. print("Matrix created from list of vectors:"): Prints a message indicating the resulting matrix.

4. print(matrix_from_list): Displays the matrix created from the list of vectors.


Comments