Re: [R] cbind a list of matrices

From: Peter Dalgaard <p.dalgaard_at_biostat.ku.dk>
Date: Sat 16 Jul 2005 - 20:20:35 EST

(Ted Harding) <Ted.Harding@nessie.mcc.ac.uk> writes:

> On 16-Jul-05 Mauro Gasparini wrote:
> >
> > Dear users,
> >
> > I have a list of several matrices with the same number of columns,
> > how do I rbind them all with a vectorized command?
> >
> > A related simpler question is, how do I vectorize the instruction
> > that rbinds together several copies of the same matrix?
>
> Didn't you simply try:
>
> > A<-matrix(c(1.1,1.2,1.3,1.4,1.5,1.6),ncol=3)
> > B<-matrix(c(2.1,2.2,2.3,2.4,2.5,2.6),ncol=3)
> > C<-matrix(c(3.1,3.2,3.3,3.4,3.5,3.6),ncol=3)
> > A
> [,1] [,2] [,3]
> [1,] 1.1 1.3 1.5
> [2,] 1.2 1.4 1.6
> > B
> [,1] [,2] [,3]
> [1,] 2.1 2.3 2.5
> [2,] 2.2 2.4 2.6
> > C
> [,1] [,2] [,3]
> [1,] 3.1 3.3 3.5
> [2,] 3.2 3.4 3.6
> > rbind(A,B,C)
> [,1] [,2] [,3]
> [1,] 1.1 1.3 1.5
> [2,] 1.2 1.4 1.6
> [3,] 2.1 2.3 2.5
> [4,] 2.2 2.4 2.6
> [5,] 3.1 3.3 3.5
> [6,] 3.2 3.4 3.6
> > rbind(A,A,A)
> [,1] [,2] [,3]
> [1,] 1.1 1.3 1.5
> [2,] 1.2 1.4 1.6
> [3,] 1.1 1.3 1.5
> [4,] 1.2 1.4 1.6
> [5,] 1.1 1.3 1.5
> [6,] 1.2 1.4 1.6
>

> If there's an exception under which the above does not work,
> I'd be interested to hear of it!

If the matrices literally are in a list, you might need

do.call("rbind", l)

which for multiple copies (5, say) of the same matrix might be done via

M <- matrix(1:4,2)
MM <- do.call("rbind",replicate(5, M, simplify=FALSE))

although it might be more efficient with

MM <- matrix(t(M),5*2,2,byrow=T)

-- 
   O__  ---- Peter Dalgaard             ěster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk)                  FAX: (+45) 35327907

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Sat Jul 16 20:24:24 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:33:46 EST