You can use the following syntax to convert a list to a matrix in R:
#convert list to matrix (by row) matrix(unlist(my_list), ncol=3, byrow=TRUE) #convert list to matrix (by column) matrix(unlist(my_list), ncol=3)
The following examples show how to use this syntax in practice.
Example 1: Convert List to Matrix (By Rows)
The following code shows how convert a list to a matrix (by rows) in R:
#create list my_list <- list(1:3, 4:6, 7:9, 10:12, 13:15) #view list my_list [[1]] [1] 1 2 3 [[2]] [1] 4 5 6 [[3]] [1] 7 8 9 [[4]] [1] 10 11 12 [[5]] [1] 13 14 15 #convert list to matrix matrix(unlist(my_list), ncol=3, byrow=TRUE) [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 [3,] 7 8 9 [4,] 10 11 12 [5,] 13 14 15
The result is a matrix with 5 rows and 3 columns.
Example 2: Convert List to Matrix (By Columns)
The following code shows how to convert a list to a matrix (by columns) in R:
#create list
my_list <- list(1:5, 6:10, 11:15)
#view list
my_list
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 6 7 8 9 10
[[3]]
[1] 11 12 13 14 15
#convert list to matrix
matrix(unlist(my_list), ncol=3)
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
The result is a matrix with 5 rows and 3 columns.
Cautions on Converting a List to Matrix
Note that R will throw an error if you attempt to convert a list to a matrix in which each position of the list doesn’t have the same number of elements.
The following example illustrates this point:
#create list
my_list <- list(1:5, 6:10, 11:13)
#view list
my_list
[[1]]
[1] 1 2 3 4 5
[[2]]
[1] 6 7 8 9 10
[[3]]
[1] 11 12 13
#attempt to convert list to matrix
matrix(unlist(my_list), ncol=3)
Warning message:
In matrix(unlist(my_list), ncol = 3) :
data length [13] is not a sub-multiple or multiple of the number of rows [5]
Additional Resources
The following tutorials explain how to perform other common conversions in R:
How to Convert List to Vector in R
How to Convert Matrix to Vector in R
How to Convert Data Frame Column to Vector in R