Open In App

How to Convert matrix to a list of column vectors in R ?

In this article, we will discuss how to convert a given matrix to a list of column vectors in R Programming Language. To do this we will take every column of the matrix and store that column in a list and at last print the list.

It can be done in these ways:



Method 1: Using split() function:

In this example to Convert a given matrix to a list of column vectors in R we use the split() function. 



Example:




# create matrix
M = matrix(100:112, ncol=3)
 
# print the matrix
display(M)
 
# create matrix to list off column vector
l =  split(M, rep(1:ncol(M), each = nrow(M)))
 
# print the list
display(l)

Output:

fig 1: Matrix

fig 2: Matrix converted to list of column vectors

Method 2: using the list() function:

In this example to Convert a given matrix to a list of column vectors in R we use the list() function 




# creating the matrix
M = matrix(100:112, ncol = 3)
 
# print the matrix
display(M)
 
# as.list() is used to convert an object into list
# as.data.frame() is used to convert as object into
# data frame M is converted into the data frame then
# that data frame is converted into the list
l<-as.list(as.data.frame(M))
 
# print the list
display(l)

Output: 

fig 3: Matrix converted to list of column vectors


Article Tags :