Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in R Programming by (7.3k points)

Goal: from a list of vectors of equal length create a matrix where each vector becomes a row.

Example:

> a <- list()

> for (i in 1:10) a[[i]] <- c(i,1:5)

> a

[[1]]

[1] 1 1 2 3 4 5

[[2]]

[1] 2 1 2 3 4 5

[[3]]

[1] 3 1 2 3 4 5

[[4]]

[1] 4 1 2 3 4 5

[[5]]

[1] 5 1 2 3 4 5

[[6]]

[1] 6 1 2 3 4 5

[[7]]

[1] 7 1 2 3 4 5

[[8]]

[1] 8 1 2 3 4 5

[[9]]

[1] 9 1 2 3 4 5

[[10]]

[1] 10  1  2  3  4  5

I want:

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

 [1,]    1    1    2    3    4    5

 [2,]    2    1    2    3    4    5

 [3,]    3    1    2    3    4    5

 [4,]    4    1    2    3    4    5

 [5,]    5    1    2    3    4    5

 [6,]    6    1    2    3    4    5

 [7,]    7    1    2    3    4    5

 [8,]    8    1    2    3    4    5

 [9,]    9    1    2    3    4    5

[10,]   10    1    2    3    4    5 

1 Answer

0 votes
by

To make a matrix from a list of vectors in R, you can use the rbind and do.call function as follows:

 for (i in 1:10) a[[i]] <- c(i,1:5)

> a

[[1]]

[1] 1 1 2 3 4 5

[[2]]

[1] 2 1 2 3 4 5

[[3]]

[1] 3 1 2 3 4 5

[[4]]

[1] 4 1 2 3 4 5

[[5]]

[1] 5 1 2 3 4 5

[[6]]

[1] 6 1 2 3 4 5

[[7]]

[1] 7 1 2 3 4 5

[[8]]

[1] 8 1 2 3 4 5

[[9]]

[1] 9 1 2 3 4 5

[[10]]

[1] 10  1  2  3  4  5

To make a matrix of the list:

> do.call(rbind, a)

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

 [1,]    1    1    2    3    4    5

 [2,]    2    1    2    3    4    5

 [3,]    3    1    2    3    4    5

 [4,]    4    1    2    3    4    5

 [5,]    5    1    2    3    4    5

 [6,]    6    1    2    3    4    5

 [7,]    7    1    2    3    4    5

 [8,]    8    1    2    3    4    5

 [9,]    9    1    2    3    4    5

[10,]   10    1    2    3    4    5

class(do.call(rbind, a))

[1] "matrix"

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...