[R] Combining matrices

Marc Schwartz marc_schwartz at me.com
Mon Aug 24 18:46:37 CEST 2009


On Aug 24, 2009, at 11:16 AM, Daniel Nordlund wrote:

> If I have two matrices like
>
> x <- matrix(rep(c(1,2,3),3),3)
> y <- matrix(rep(c(4,5,6),3),3)
>
> How can I combine  them to get ?
>
> 1 1 1 4 4 4
> 1 1 1 5 5 5
> 1 1 1 6 6 6
> 2 2 2 4 4 4
> 2 2 2 5 5 5
> 2 2 2 6 6 6
> 3 3 3 4 4 4
> 3 3 3 5 5 5
> 3 3 3 6 6 6
>
> The number of rows and the actual numbers above are unimportant,  
> they are given so as to illustrate how I want to combine the  
> matrices.  I.e., I am looking for a general way to combine the first  
> row of x with each row of y, then the second row of x with y, ....
>
> Thanks,
>
> Dan



nr.x <- nrow(x)
nr.y <- nrow(y)

 > cbind(x[rep(1:nr.x, each = nr.x), ], y[rep(1:nr.y, nr.y), ])
       [,1] [,2] [,3] [,4] [,5] [,6]
  [1,]    1    1    1    4    4    4
  [2,]    1    1    1    5    5    5
  [3,]    1    1    1    6    6    6
  [4,]    2    2    2    4    4    4
  [5,]    2    2    2    5    5    5
  [6,]    2    2    2    6    6    6
  [7,]    3    3    3    4    4    4
  [8,]    3    3    3    5    5    5
  [9,]    3    3    3    6    6    6



HTH,

Marc Schwartz




More information about the R-help mailing list