Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

r - Combine a list of matrices to a single matrix by rows

Let's say I have a list of matrices (all with the same number of columns). How would I append / combine these matrices by row ('row bind', rbind) to get a single matrix?

Sample:

> matrix(1, nrow=2, ncol=3)
     [,1] [,2] [,3]
 [1,]    1    1    1
 [2,]    1    1    1
> matrix(2, nrow=3, ncol=3)
     [,1] [,2] [,3]
[1,]    2    2    2
[2,]    2    2    2
[3,]    2    2    2
> m1 <- matrix(1, nrow=2, ncol=3)
> m2 <- matrix(2, nrow=3, ncol=3)

Now we can have many matrices in a list, let's say we have only two:

l <- list(m1, m2)

I would like to achieve something like:

> rbind(m1, m2)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    2    2    2
[4,]    2    2    2
[5,]    2    2    2

I can easily do it on 2 matrices but I am not sure how to do it with a list of matrices.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use do.call(rbind,...)

> m1 <- matrix(1, nrow=2, ncol=3)
> m2 <- matrix(2, nrow=3, ncol=3)
> l <- list(m1, m2)
> do.call(rbind, l)
     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    1    1    1
[3,]    2    2    2
[4,]    2    2    2
[5,]    2    2    2

You may also be interested in the rbind.fill.matrix() function from the "plyr" package, which will also let you bind matrices with differing columns, filling in with NA where necessary.

> m1 <- matrix(1, nrow=2, ncol=3)
> m2 <- matrix(2, nrow=3, ncol=4)
> l <- list(m1, m2)
> library(plyr)
> rbind.fill.matrix(l)
     1 2 3  4
[1,] 1 1 1 NA
[2,] 1 1 1 NA
[3,] 2 2 2  2
[4,] 2 2 2  2
[5,] 2 2 2  2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...