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:
- Using the split() function
- Using list() with data.frame()
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.
- The split() function is used to split the data according to our requirement.
- The arguments given in the split() function are data itself and the other one is rep() function
- The rep() function is used to replicates the data and in the rep() function we give one argument i.e. nrow() so, that the sequence is generated row-wise
- In nrow() function we give the data as an argument. “each = nrow()” is used to repeat this process for each row.
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
- The list() function is used with the “as.” command. This command is used to convert the object into a list and the object can be any kind of data structure i.e. data frame, matric, vector, etc.
- The argument in the list() function is as.data.frame. So basically, what we are doing here is? At first, we convert a matrix into the data frame by using as.data.frame() then we convert that data frame into the list and at last, print that list.
- In our case what happens is as.list() takes every single column of the data frame and put every element of data frame’s column into a list, store that lists into “l” and prints the l.