Data structures in R includes lists and matrices. A list is a one-dimensional data structure that can hold objects of different data types. A list is created using the list() function. A Matrix is a two-dimensional data structure that can hold objects of the same data types. Matrices are created using the matrix() function. This guide explains how to convert a list in R into a matrix.
Unlist function in R
To convert a List in R to a Matrix, you need the matrix() function and the unlist() function as an argument. The unlist() function converts a list to a vector.
Syntax
unlist(x)
Arguments
x = a list
Matrix function in R
To create a matrix, you need to call the matrix() function. By default, matrices are in column-wise order.
Syntax
matrix(data, ncol, nrow, byrow)
Arguments
- data = input vector
- ncol = number of columns to be created
- nrow = number of rows to be created
- byrow = Either TRUE or FALSE. By default, it’s set to FALSE and arranges elements by column.
List to Matrix in R
Let’s see a simple example of converting a List to a Matrix.
Creating a list
demo_list<-list(1, 2, 3, 4, 5, 6, 7, 8, 9)
Converting a list to a matrix arranged column-wise
matrix(unlist(demo_list), ncol=3)
Converting a list to a matrix arranged row-wise
matrix(unlist(demo_list), ncol=3, byrow=TRUE)
As mentioned above, matrix() takes a vector as an input. This is why we used the unlist() function to convert the list to a vector and then used it as an input for the matrix() function. The byrow argument allows us to control the arrangement of the elements of the input vector. If TRUE, then the input vector is arranged row-wise.