VOOZH about

URL: https://www.geeksforgeeks.org/r-language/create-a-matrix-from-a-list-of-vectors-using-r/

⇱ Create a matrix from a list of vectors using R - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create a matrix from a list of vectors using R

Last Updated : 23 Jul, 2025

In R, vectors can be integer, double, character, logical, complex and raw types. A vector is created using the c() function:

a <- c(val1, val2, ...

Creating a List of Vectors

A list of vectors in R is an array of more than one vector kept in a list structure. Creating a list of vectors is done in the following way:


Output
[1] "The list of vectors is: "
[[1]]
[1] 1 2 3 4

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

[[3]]
[1] 3 4 5 6

[[4]]
[1] 4 5 6 7

[[5]]
[1] 5 6 7 8

Matrix from List of Vectors

Matrices in R can be formed from a list of vectors with the help of functions such as do.call() and matrix().

Using do.call() Function

do.call() helps you execute a function (such as rbind()) on a list of arguments. Here's how to use it to form a matrix:

Output:

[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 2 3 4 5
[3,] 3 4 5 6
[4,] 4 5 6 7
[5,] 5 6 7 8

we call the do.call() function and pass the arguments as rbind and a.

Using matrix() Function

The matrix() function is used to transform a list of vectors into a matrix. To accomplish this, we first transform the list into a single vector with unlist(), then form the matrix:

Syntax:

matrix(data, nrow, ncol, byrow, dimnames)

Where,

  • data: is the input vector which represents the elements in the matrix
  • nrow: specifies the number of rows to be created
  • ncol: specifies the number of columns to be created
  • byrow: specifies logical value. If TRUE, matrix will be filled by row. Default value is FALSE.
  • dimnames: specifies the names of rows and columns

Output
 [,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 3 4 5 6
[3,] 3 4 5 6 7
[4,] 4 5 6 7 8
[5,] 5 6 7 8 9
[6,] 6 7 8 ...
Comment

Explore