R Program to convert a given matrix into a list

How to convert a given matrix into a list

Here we are explaining how to write an R program to convert a given matrix into a list. Here we are using a built-in function matrix() for this conversion. This method helps to creates a matrix from the given set of values. The syntax of this function is,

matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,dimnames = NULL)

NA: An optional data vector.

nrow: The desired number of rows.

ncol: The desired number of columns.

byrow: If FALSE (the default) the matrix is filled by columns, otherwise filled by rows.

dimnames: NULL or a list of length 2 giving the row and column names respectively.

How to convert a given matrix into a list in the R Program

Below are the steps used in the R program to convert a given matrix into a list. In this R program, we directly give the values to built-in functions. And print the function result. Here we used variables Matx for assigning matrix. And create the matrix. Finally use split() method which helps to divide the vector or data frame containing values into groups. The rep() method replicates the values.

ALGORITHM

STEP 1: Assign variable Matx with matrix values

STEP 2: Create a matrix with 2 rows and 2 columns

STEP 3: Create by calling like  matrix(1:8,nrow=2, ncol=2)

STEP 4: print the original matrix

STEP 5: Convert the matrix into list by using split(),rep()

STEP 6: Finally print the converted lists

 

R Source Code

                                          Matx = matrix(1:8,nrow=2, ncol=2)
print("Original matrix:")
print(Matx)
L= split(Matx, rep(1:ncol(Matx), each = nrow(Matx)))
print("list from the matrix:")
print(L)
                                      

OUTPUT

[1] "Original matrix:"
     [,1] [,2]
[1,]    1    3
[2,]    2    4
[1] "list from the matrix:"
$`1`
[1] 1 2

$`2`
[1] 3 4