How to Convert List to Matrix in R

To convert List to Matrix in R, you can use the “matrix()” function and pass the “unlist(list)” function as an argument to the matrix() function. The “unlist()” method returns a vector that contains all the atomic components which occur in list data, and the “matrix()” function will convert the vector into a matrix.

Syntax

# 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)

Example 1: Converting a list to a matrix by rows

main_list <- list(1:4, 5:8, 9:12)

matrix(unlist(main_list), ncol = 3, byrow = TRUE)

Output

     [,1]  [,2]  [,3]
[1,]   1    2     3
[2,]   4    5     6
[3,]   7    8     9
[4,]  10   11    12

In the above code, we converted the list main_list into a matrix by first converting a list to a vector using unlist() and then reshaping it into a matrix using the matrix() function.

Example 2: Converting a list to a matrix by columns

main_list <- list(1:5, 6:10, 11:15)

matrix(unlist(main_list), ncol = 3)

Output

     [,1]  [,2]  [,3]
[1,]   1    6     11
[2,]   2    7     12
[3,]   3    8     13
[4,]   4    9     14
[5,]   5   10     15

In the above code, we converted the list main_list into a matrix by first converting it into a vector using unlist() function and reshaping it into a matrix using the matrix() function.

Error while Converting a List to Matrix

R raises the “data length [11] is not a sub-multiple or multiple of the number of rows” error if you attempt to convert a list to a matrix in which each list position doesn’t have the same number of elements.

Example

main_list <- list(1:4, 6:9, 10:12)

matrix(unlist(main_list), ncol = 3)

Output

     [,1] [,2] [,3]
[1,]  1    6    10
[2,]  2    7    11
[3,]  3    8    12
[4,]  4    9    1

Warning message:

In matrix(unlist(main_list), ncol = 3) :
data length [11] is not a sub-multiple or multiple of the number of rows [4]

To fix the data length [11] is not a sub-multiple or multiple of the number of rows [4] error, provide the same number of elements to the matrix.

main_list <- list(1:4, 6:9, 10:13)

matrix(unlist(main_list), ncol = 3)

Output

     [,1] [,2]  [,3]
[1,]  1    6     10
[2,]  2    7     11
[3,]  3    8     12
[4,]  4    9     13

That’s it.

Leave a Comment