Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...