How to Convert List to Matrix in R

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

  1. data = input vector
  2. ncol = number of columns to be created
  3. nrow = number of rows to be created
  4. 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)
Column-wise matrix
Converting a list to a matrix arranged column-wise.

Converting a list to a matrix arranged row-wise

matrix(unlist(demo_list), ncol=3, byrow=TRUE)
Row-wise matrix
Converting a list to a matrix arranged row-wise.

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.

Leave a Comment