How to Convert List to Matrix in R Programming

List in R is an inbuilt data structure having elements of different data types. A Vector containing all elements of the different types called List in R. Matrix is a two-dimensional data structure in R. A matrix is a collection of elements arranged in a two-dimensional rectangular layout.

List to Matrix in R

To convert R List to Matrix, use the matrix() function and pass the unlist(list) as an argument. The unlist() method in R simplifies it to produce a vector that contains all the atomic components which occur in list data.

If you want to convert the list into a m x n matrix, where each element of the list corresponds to a column in the matrix, use the following syntax.

Syntax

matrix(unlist(z), ncol =, nrow =)

To give a perfect example, let’s create four vectors: rv1, rv2, rv3, and rv4.

rv1 <- 1:5
rv2 <- 6:10
rv3 <- 11:15
rv4 <- 16:20

To convert vector to list, use the list() function and pass all the vectors in the argument.

rv1 <- 1:5
rv2 <- 6:10
rv3 <- 11:15
rv4 <- 16:20

data <- list(rv1, rv2, rv3, rv4)
data

To see the list, go to the terminal, and type the following command.

RScript Pro.R

It will give us the following output.

[[1]]
[1] 1 2 3 4 5

[[2]]
[1] 6 7 8 9 10

[[3]]
[1] 11 12 13 14 15

[[4]]
[1] 16 17 18 19 20

To convert the list to matrix, use the matrix() function. The matrix() function takes three parameters.

  1. data: unlist(data)
  2. ncol
  3. nrow

We will create a 5×4 matrix. See the following code.

rv1 <- 1:5
rv2 <- 6:10
rv3 <- 11:15
rv4 <- 16:20

data <- list(rv1, rv2, rv3, rv4)

mtrx <- matrix(unlist(data), ncol = 4, nrow = 5)
mtrx

Output

    [,1] [,2] [,3] [,4]
[1,]  1   6    11   16
[2,]  2   7    12   17
[3,]  3   8    13   18
[4,]  4   9    14   19
[5,]  5  10    15   20

That is it. You have now converted a list into the matrix.

See also

R list to data frame

R list to vector

R list to string

Leave a Comment