Convert Matrix to List of Column-Vectors in R (2 Examples)
In this R article you’ll learn how to divide a matrix into a list of column-vectors.
The article will contain the following:
Let’s dig in.
Introducing Example Data
We’ll use the data below as basement for this R programming tutorial:
data <- matrix(1:15, ncol = 3)# Create example matrix data # Print example matrix
Have a look at the previous table. It shows that our example matrix has five data points and three columns.
Example 1: Split Matrix into List of Column-Vectors Using split(), rep(), ncol() & nrow()
This example illustrates how to use the split, rep, ncol, and nrow functions to convert the columns of a matrix into a list of vectors.
Have a look at the following R code:
my_list1 <- split(data, # Split matrix into list rep(1:ncol(data), each = nrow(data))) my_list1 # Print list of column-vectors # $`1` # [1] 1 2 3 4 5 # # $`2` # [1] 6 7 8 9 10 # # $`3` # [1] 11 12 13 14 15 #
As you can see in the RStudio console, we have created a list object containing three list elements. Each of these list elements contains the values of one of the matrix columns.
Example 2: Split Matrix into List of Column-Vectors Using lapply(), seq_len(), ncol() & function()
In Example 2, I’ll show an alternative to the R code of Example 1 that is based on the lapply, seq_len, ncol, and function commands.
Consider the following R programming syntax:
my_list2 <- lapply(seq_len(ncol(data)), # Split matrix into list function(x) data[ , x]) my_list2 # Print list of column-vectors # [[1]] # [1] 1 2 3 4 5 # # [[2]] # [1] 6 7 8 9 10 # # [[3]] # [1] 11 12 13 14 15 #
Te list that we have created in this example is the same as in Example 1. Which code you want to use is a matter of taste.
Video & Further Resources
Have a look at the following video of my YouTube channel. I’m explaining the examples of this article in the video.
In addition, you could have a look at the other tutorials on https://www.statisticsglobe.com/.
- Convert Row Names into Column of Data Frame
- Convert Matrix to Vector in R
- Split Data Frame into List of Data Frames Based On ID Column
- Convert List of Vectors to Data Frame
- All R Programming Examples
You have learned in this article how to split the variables of a matrix into a list of vectors in the R programming language. Let me know in the comments below, if you have additional questions.